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}hello\n}\nline2}abc".replace(/(.*)}/g, "$1");
// "line1hello\n\nline2abc"
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.
>Solution :
You just need to change the modifier from g (global) to s (single line):
"line1}hello\n}\nline2}abc".replace(/(.*)}/s, "$1");
// "line1}hello\n}\nline2abc"
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.