1

I'm trying to use JS to replace a specific string within a string that contains html tags+attributes and styles while avoiding the inner side of the tags to be read or matched (and keep the original tags in the text).

for example, I want <span> this is span text </span> to be become: <span> this is s<span class="found">pan</span> text </span> when the keyword is "pan"

I tried using regex with that .. My regex so far:

$(this).html($(this).html().replace(new RegExp("([^<\"][a-zA-Z0-9\"'\=;:]*)(" + search + ")([a-zA-Z0-9\"'\=;:]*[^>\"])", 'ig'), "$1<span class='found'>$2</span>$3"));

This regex only fails in cases like <span class="myclass"> span text </span> when the search="p", the result:

<s<span class="found">p</span>an class="myclass"> s<span class="found">p</span>an text</s<span class="found">p</span>an>

*this topic should help anyone who seeks to find a match and replace the matched string while avoiding strings surrounded by specific characters to be replaced.

1 Answer 1

4

As thg435 say, the good way to deal with html content is to use the DOM.

But if you want to avoid something in a replace, you can match that you want to avoid first and replace it by itself.

Example to avoid html tags:

var text = '<span class="myclass"> span text </span>';

function callback(p1, p2) {
    return ((p2==undefined)||p2=='')?p1:'<span class="found">'+p1+'</span>';
}

var result = text.replace(/<[^>]+>|(p)/g, callback);

alert(result);
Sign up to request clarification or add additional context in comments.

3 Comments

I recommend this method, it is faster as it has no major loops .. thanks a lot
Perhaps, however keep in mind that the callback function is called at each occurence
oops; this method has a problem with chrome, it mis-executes the regex somehow it replaces spaces and other tags too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.