Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 606
d0n.key Avatar asked Dec 14 '25 02:12

d0n.key


1 Answers

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
})
like image 145
Damon Avatar answered Dec 15 '25 15:12

Damon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!