简体   繁体   中英

Regular-Expression capture word in html tag

I try to replace some HTML-Tags in a code snippet. Eg a span-element is to replace when it has no id, but it isn't to replace when it has an id.

Here is my approach:

var sHTML = 'Text abc <span> text def ';
sHTML = sHTML.replace(/<\s*\/*\s*span(.[^(id\=)]*){0,1}?>/ig, '');
alert(sHTML);

It works wrong! Because it must not replace when "id=" occurs, but in case of occur of some single character like "i" or "d" or "=" it shouldn't make any difference, and it has to replace. In other words, I expect for: var sHTML = 'Text abc <span id=MyId > text def '; Nothing is to replace, because the span-element has an id, so it should be remain as it is as follows: Text abc <span id=MyId > text def .

But for var sHTML = 'Text abc <span style="color:#00ff00;" > text def '; var sHTML = 'Text abc <span style="color:#00ff00;" > text def '; it has to replace, because the span-element has no id as follows: Text abc text def .

Any idea? Thanks in advance.

<span (?![^>]*id)[^>]*>[ ]*|<\/span>

Try this.See demo.

https://regex101.com/r/vD5iH9/82

var re = /<span (?![^>]*id)[^>]*>[ ]*|<\/span>/gim;
var str = 'Text abc <span style="color:#00ff00;" > text def \'; \nText abc <span id=MyId > text def \nText <span color="red" >abc</span>';
var subst = '';

var result = str.replace(re, subst);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM