Rees
Rees

Reputation: 1787

regex help. modify regex to exclude content within curly braces

In javascript, my regex is:

let regEx = new RegExp("([A-Za-z])(?!([^<]+)?>)", "gi");

My string is:

<span class="customer-key">{aaa}</span>bbb {ccc}

In the above example, the regex matches "aaa", "bbb" and "ccc".

I would like to update my regex to EXCLUDE anything WITHIN curly braces, so that it ONLY matches "bbb".

How can I update the regex to do so? thanks!

Upvotes: 0

Views: 88

Answers (2)

The fourth bird
The fourth bird

Reputation: 163372

If you want to get bbb , one option could be to use the dom, find the textnode(s) and remove the content between curly braces:

const htmlString = `<span class="customer-key">{aaa}</span>bbb {ccc}`;
let div = document.createElement('div');
div.innerHTML = htmlString;
div.childNodes.forEach(x => {
  if (x.nodeType === Node.TEXT_NODE) {
    console.log(x.textContent.replace(/{[^}]+}/g, ''));
  }
});

Note that parsing html with a regex is not advisable.

If you want to get bbb from your example string, another option could be to match what you don't want to keep and to replace that with an empty string.

const regex = /\s*<[^>]+>\s*|\s*{[^}]+}\s*/gm;
const str = `<span class="customer-key">{aaa}</span>bbb {ccc}`;
const result = str.replace(regex, '');
console.log(result);

Upvotes: 2

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92477

Try (your regexp separate letters so my too)

let regEx = new RegExp("([A-Za-z])(?!([^<]+)?>)(?!([^{]+)?})", "gi");
let str= '<span class="customer-key">{aaa}</span>bbb {ccc}'

let s =str.match(regEx);

console.log(s)

Upvotes: 3

Related Questions