Matching a string that is not preceded by another string is a negative lookbehind and not supported by JavaScript's regex engine. You can however do it using a callback.
Given
str = "sssHi this is the test for regular Expression,sr,Hi this is the test for regular Expression"
Use a callback to inspect the character preceding str
:
str.replace(/(.)Hi this is the test for regular Expression$/g, function($0,$1){ return $1 == "s" ? $0 : $1 + "replacement"; })
// => "sssHi this is the test for regular Expression,sr,replacement"
The regex matches both strings so the callback function is invoked twice:
- With
$0 = "sHi this is the test for regular Expression"
$1 = "s"
- With
$0 = ",Hi this is the test for regular Expression"
$1 = ","
If $1 == "s"
the match is replaced by $0
, so it remains unchanged, otherwise it is replaced by $1 + "replacement"
.
Another approach is to match the second string, i.e. the one you want to replace including the separator.
To match str
preceded by a comma:
str.replace(/,Hi this is the test for regular Expression/g, ",replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"
To match str
preceded by any non-word character:
str.replace(/(\W)Hi this is the test for regular Expression/g, "$1replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"
To match str
at the end of line:
str.replace(/Hi this is the test for regular Expression$/g, "replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"