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.
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With