Unknown Unknown - 1 year ago 104
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
into a
, but only, if there is no
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
that is not followed by a
, because this is the main difficulty here.


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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download