Maximus Maximus - 1 year ago 54
Javascript Question

How to match a string with leading and trailing conditions and a matching group

I want to match string

that is not preceded or followed by another quote. I can use negative look-ahead for the trailing quote, but can't figure out how to implement negative look-behind. With this string:

'4' = "$NULL$" AND '3' = """$NULL$" AND '7' = """$NULL$"""

It should match only first
. Here is the regexp that I've put up:


But it's missing look-behind.

I've seen many answers suggesting imitating negative look-behind with
function, but I can't understand how this can be done with negative look-ahead and capturing.

Answer Source

You may use a capturing group and use a backreference in the replacement pattern:

var regex = /(^|[^"])("\$NULL\$")(?!")/g;
var str = `'4' = "\$NULL\$" AND '3' = """\$NULL\$" AND '7' = """\$NULL\$"""`;
console.log(str.replace(regex, "$1[NEW_VAL]$2[/NEW_VAL]"));


  • (^|[^"]) - Group 1 (referred to as $1 from the replacement pattern) capturing the start of string (^) or any char other than "
  • ("\$NULL\$") - Group 2 (referred to as $2 from the replacement pattern) capturing "$NULL$" string
  • (?!") - that is not followed with "
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download