Reputation: 21
After much searching I am still stumped. How do I match everything in a string except what matches a given pattern.
I have found solutions for negating specific words or character sets using the ^
or negative look ahead, but I need a solution to negate anything that matches a specific pattern.
Example text (snippet of html):
abcd efg hijkl <span class='skipMe'>xxx</span> nop qrst uv wxyz.
I want to match everything except the whole span tag. i.e. everything except
/<span.*?<\/span>/
Any leads are appreciated.
Upvotes: 2
Views: 247
Reputation:
Using regular expressions in this way is extremely naive and prone to unwanted side-effects. My recommendation would be to use the built-in DOM API.
Create a wrapper element, set the value of the innerHTML
property to the input string, query the wrapper element for the element in question, remove the element in question, then return the value of the innerHTML
property.
Here's an example:
const input = "abcd efg hijkl <span class='skipMe'>xxx</span> nop qrst uv wxyz.";
const func = input => {
const wrapper = Object.assign(document.createElement('div'), { innerHTML: input });
wrapper.querySelector('.skipMe').remove()
return wrapper.innerHTML;
};
console.log(func(input));
One caveat of this approach is that the HTML is passed to the parser, so if the HTML is not valid, scary things will happen
Upvotes: 0
Reputation: 16777
You could always split your text on the regex like this:
var text = 'abcd efg hijkl <span class="skipMe">xxx</span> nop qrst uv wxyz.'
console.log(
text.split(/<span.*?<\/span>/)
)
Upvotes: 1