D
D
DanKud2018-07-11 23:05:54
JavaScript
DanKud, 2018-07-11 23:05:54

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

3 answer(s)
S
Sergey Sokolov, 2018-07-11
@sergiks

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) {
  // нашлось
}

E
eternalfire, 2018-07-11
@eternalfire

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}`);
    });
}

P
Pavel Kornilov, 2018-07-12
@KorniloFF

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 question

Ask a Question

731 491 924 answers to any question