Sara
Sara

Reputation: 21

Match everything except a specific pattern in JavaScript

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

Answers (3)

user4639281
user4639281

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

gyre
gyre

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

Choo Hwan
Choo Hwan

Reputation: 416

console.log('abcd efg hijkl <span class=\'skipMe\'>xxx</span> nop qrst uv wxyz.'.replace(/<(|\/)span[^>]*>/g, ''));

//OR variant #2

console.log('abcd efg hijkl <span class=\'skipMe\'>xxx</span> nop qrst uv wxyz.'.replace(/\s<span.+span>?/g, ''));

SEE

Upvotes: 0

Related Questions