How To Create A Regular Expression For A Span Attribute?
Ok, I admit it, I suck at Regular Expressions. I'm trying to get the value of attribute data-hover-id. I have the following javascript code: var editText = ';
var result = re.exec(str)[1];
Edit: If you need to account for no quotes at all try this one:
/data-hover-id=['"]?([^\s>]+)['"]?/
Solution 2:
One easy way (avoiding the messy string-manipulation):
var editText = "<span class='hover-content' data-hover-id='2' >Some text</span>",
tmp = document.createElement('div');
tmp.innerHTML = editText;
tmp.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(tmp);
var hoverId = tmp.getElementsByTagName('span')[0].getAttribute('data-hover-id');
tmp.parentNode.removeChild(tmp);
alert(hoverId);
However, given that:
This string is be manipulated.
I'll also offer:
var editText = "<span class='hover-content' data-hover-id='2' >Some text</span>",
parts = editText.split(/\s+/),
hoverId = -1;
for (var i = 0, len = parts.length; i < len; i++) {
if (parts[i].indexOf('data-hover-id') == 0) {
hoverId = parseInt(parts[i].split('=')[1].match(/\d+/), 10)
}
}
console.log(hoverId);
And a more concise (though perhaps fragile) solution:
var editText = '<span class="hover-content" data-hover-id=2 >Some text</span>',
hoverId = editText.match(/\s?data\-hover\-id=(?:['"])?(\d+)(?:['"])?/)[1] || -1;
console.log(hoverId);
Works with single-quoted ('
) attribute-values: JS Fiddle demo.
Works with double-quoted ("
) attribute-values: JS Fiddle demo.
Work with unquoted values: JS Fiddle demo.
Post a Comment for "How To Create A Regular Expression For A Span Attribute?"