Answer the question
In order to leave comments, you need to log in
How to extract an attribute from a tag using a regular expression?
There is an HTML tag line with attributes. For example string How can I extract attribute values from this string using JavaScript regular expression ? <span name="two">text</span>
name
Answer the question
In order to leave comments, you need to log in
You can create a node without regular expressions and get its attribute:
var s = '<span toster="two">text</span>';
var el = document.createElement('div');
el.innerHTML = s;
var span = el.children[0];
var value;
var attrs = span.attributes;
for(let i = 0; i < attrs.length; i++) {
if( attrs[i].name === 'toster') {
value = attrs[i].value;
break;
}
}
if(value) {
// нашлось
}
const regex = /([^"\\]*(?:\\.[^"\\]*)*)/gm;
const str = `<span name="two">text</span>`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
UPD - read the question inattentively. Corrected it for finding the value of the attribute.
UPD 2 - If the operation is frequent, then it is easier to use this function:
function _getAttr (str, attr) {
return new RegExp(attr + "\s*=\s*([\"\'])([^\"\']+)\\1").exec(str)[2];
}
console.log(_getAttr('<span name="two">text</span>', 'name'));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question