How to replace the last occurence of } in a multiline string in Javascript?
The method from how to replace last occurrence of a word in javascript? doesn’t work in the case of a multiline string:
"line1}hellon}nline2}abc".replace(/(.*)}/g, "$1");
// "line1hellonnline2abc"
because in this case every }
is replaced, which I don’t want.
Note: it’s not a duplicate of Replace last occurrence of character in string because my question is specifically about multiline strings, and the linked question is not.
3
Answers
You just need to change the modifier from
g
(global) tos
(single line):You don’t need
g
at all since you want to perform a single match.By default, the regex is performed per line, but using
s
will treat the input string as a single line.You can use
/}(?=[^n]*$)/gm
for remove}
in every line.This regex works by looking for a
}
character that is not followed by another}
character anywhere at the rest of the string.You can use something like this:
Regex explanation:
/
– start delimiter}
– find literal closing curly brace(?=[^}]*$)
– ahead of me is no other closing curly brace till the end of the string (not line)/
– end delimiterBy not using the multiline flag
/m
, the$
behaves as a end-of-string meta escape instead of end-of-line.https://regex101.com/r/Ausg5r/1
Do note that PCRE has a dedicated meta escape for end-of-string
z
but JS does not.