0

I have a list of javascript string with HTML tags and want to split the tags.

<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />
<section id = "test">

I tried to split by double quotes (") but getting only

class=", logo"

I want to split in the following array

[class="logo"], [src="http://i.imgur.com/z38lrml.png"],[height="60px"]

and so on for the next line.

Is there anyway to separate?

Thank you

4
  • So, you want an array of objects where each object has a single key value pertaining to each attribute in the element? Commented Jun 13, 2019 at 17:42
  • And I do mean object because [class="logo"] is not a valid array. Commented Jun 13, 2019 at 17:43
  • if you really wanna do this from strings.. split on spaces. reduce that to only look for strings that contain '=' ?? otherwise developer.mozilla.org/en-US/docs/Web/API/Element/attributes Commented Jun 13, 2019 at 17:44
  • nvm, splitting on spaces is flawed. but element.attributes is still relevant maybe Commented Jun 13, 2019 at 17:45

2 Answers 2

2

It seems your HTML tag is actually just a string? In that case, you can use regex:

let html = '<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />';
let attributes = html.match(/[\w-]+="[^"]*"/g);
console.log(attributes);

Sign up to request clarification or add additional context in comments.

Comments

0

const attributes = document.querySelector('img').getAttributeNames();
const img = document.querySelector('img');

const output = [...attributes].map((attr) => {
  const val = img.getAttribute(attr);
  return `${attr}" = "${val}`;
});

console.log(output);
<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />

Edit --

If your html is a string, use DOMParser to convert it into html.

const str = `<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />
<section id = "test">`;

const dom = new DOMParser().parseFromString(str, 'text/html');

let output = [];
[...dom.body.children].forEach((node) => {
    const attributes = node.getAttributeNames();
    output.push([...attributes].map((attr) => {
        const val = node.getAttribute(attr);
        return `${attr}" = "${val}`;
    }));
})

console.log(output);

5 Comments

@randomSoul, I will have more than 100 lines of HTML tags
Check your quotes ;) "class\" = \"logo"
@BinitaGyawali "I will have more than 100 lines..." - And the problem is?
@Andreas - The quotes are perfect when run in the browser.
Your script outputs <attributeName>" = "<value> instead of <attributeName> = "<value>"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.