Unknown Unknown - 29 days ago 11
Javascript Question

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.

EDIT:

Okay, so with Damon's help, I was able to solve my problem:

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

Answer

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 !?

Comments