skip to Main Content

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


  1. You just need to change the modifier from g (global) to s (single line):

    "line1}hellon}nline2}abc".replace(/(.*)}/s, "$1");
    // "line1}hellon}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.

    Login or Signup to reply.
  2. You can use /}(?=[^n]*$)/gm for remove } in every line.

    const str = "line1}hellon}nline2}abc";
    
    const result = str.replace(/}(?![sS]*})/, '|');
    
    console.log(result)

    This regex works by looking for a } character that is not followed by another } character anywhere at the rest of the string.

    Login or Signup to reply.
  3. You can use something like this:

    const str = `line1}hello
    }
    line2}abc`;
    
    const result = str.replace(/}(?=[^}]*$)/, '');
    
    console.log(result)

    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 delimiter
    • Notice no flags; important

    By 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search