Search code examples
javascriptregexreplaceescapingcurly-braces

How to represent a curly brace in regex replace using javascript


I want to be able to do the following string replacement:

Input: 3^4
Output: 3^{4}

I have written the following regex expression to solve it:

outputString=outputString.replace(/\^(-?[1-9][0-9]*)/g,"\^"+"{"+"$1"+unescape('}'));

The output escapes the braces to be something like: 3^/{4/}

Can someone suggest a solution to this?


Solution

  • Try this regex:

    '3^4'.replace(/\^(\d+)/, '^{$1}');  // -> 3^{4}