d0n.key
d0n.key

Reputation: 1483

JavaScript Regex (replace) if absence of word after other word

Imagine I have the following string:

b(hello world)b

Now I want to turn the b(into a b(<b>, but only, if there is no <b>already added. This is what I got so far:

var string = "abc b(yolo)b cba";   
string.replace("b\((?!<b>)", "b(<b>");

Unfortunately I've never used Regex statements before, so I have like no idea what I'm doing, and it's not working...

So, if you understand my problem please provide the answer, and maybe explain how you seeked for a b( that is not followed by a <b>, because this is the main difficulty here.

Upvotes: 3

Views: 78

Answers (1)

Damon
Damon

Reputation: 4336

try this:

string.replace(/b\((?!<b>)/g, 'b(<b>')

You were on the right track, but a string is not a valid regex in javascript, and negative lookahead is ?! not !?

Edit - your followup question

You would need a negative lookbehind to first check if the </b> comes before the )b. Javascript regex engine does not support lookbehind, but you can achieve this with a callback instead:

string.replace(/(<\/b>)?\)b/g, (m, c) => c ? m : `</b>${m}`)

or if es6 is not supported

string.replace(/(<\/b>)?\)b/g, function (m, c) {
 return c ? m : '</b>' + m
})

Upvotes: 3

Related Questions