nemesis
nemesis

Reputation: 68

extjs 4.2 - replace substring, but avoid changing tags

In a given string, e.g. "This <TERM>is</TERM> my question <TERM>for</TERM> you", I need to replace a substring.

Goal: surround substring with <MARK>-Tags for highlighting.

Example:

substring: 'e'

desired result: This <TERM>is</TERM> my qu<mark>e</mark>stion <TERM>for</TERM> you

actual result: This <T<mark>E</mark>RM>is</T<mark>E</mark>RM> my qu<mark>e</mark>stion <T<mark>E</mark>RM>for</T<mark>E</mark>RM> you

How can I prevent the pseudoTags <TERM> and </TERM> from beeing changed?

Until now, I used this:

according to my example, filterValue would be substring 'e'

var filterStartTag = '<mark>';
var filterEndTag = '</mark>';
var replaceFilterValue = filterStartTag + filterValue + filterEndTag;
value = value.replace(new RegExp(filterValue, 'gi'), replaceFilterValue);

I need to find a solution where also substrings like "t", "te", "erm" (and so on) can properly be replaced.

Any help would be highly appreciated.

Upvotes: 1

Views: 3969

Answers (1)

kevhender
kevhender

Reputation: 4405

Try something like this: value.replace(/(e)+(?![^<]*>)/g, "$1");

The (e) is what is interpreted as $1 for your replacement, and can be replaced with any Regex that matches what you need (keep it surrounded by parentheses to allow for the $1 replacement). So, you could also do it like this, to be more dynamic:

var r = new RegExp("(" + filterValue + ")+(?![^<]*>)", "gi");
value.replace(r, "<mark>$1</mark>");

Essentially, this is saying to match anything in the first parentheses, unless it is surrounded by tags (?![^<]*>).

Upvotes: 1

Related Questions