ryan
ryan

Reputation: 6655

Match a word unless it is preceded by an equals sign?

I have the following string

class=use><em>use</em>

that when searched using us I want to transform into

class=use><em><b>us</b>e</em>

I've tried looking at relating answers but I can't quite get it working the way I want it to. I'm especially interested in this answer's callback approach.

Help appreciated

Upvotes: 1

Views: 92

Answers (3)

TimoStaudinger
TimoStaudinger

Reputation: 42460

If you can make any assumptions about the structure of your document, you may be better off using an approach that operates on DOM elements directly rather than parsing the whole document with a regex.

Parsing HTML with a regex has certain problems that can be painful to deal with.

var element = document.querySelector('em');

element.innerHTML = element.innerHTML.replace('us', '<b>us</b>');
<div class=use><em>use</em>
</div>

Upvotes: 2

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

This is a good exercise for writing regular expressions, and here's a possible solution.

"useclass=use><em>use</em>".replace(/([^=]|^)(us)/g, "$1<b>$2</b>");

// returns "<b>us</b>eclass=use><em><b>us</b>e</em>"

([^=]|^) ensures that the prefix of any matched us is either not an equal sign, or it's the start of the string.

As @jamiec pointed out in the comments, if you are using this to parse/modify HTML, just stop right now. It's mathematically impossible to parse a CFG with a regular grammar (even with enhanced JS regexps you will have a bad time trying to achieve that.)

Upvotes: 3

nwalton
nwalton

Reputation: 2061

I would first look for any character other than the equals sign [^=] and separate it by parentheses so that I can use it again in my replacement. Then another set of parentheses around the two characters us ought to do it:

var re = /([^=]|^)(us)/

That will give you two capture groups to work with (inside the parentheses), which you can represent with $1 and $2 in your replacement string.

str.replace( /([^=|^])(us)/, '$1<b>$2</b>' );

Upvotes: 0

Related Questions