Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace the last occurence of } in a multiline string in Javascript?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading