Regular expression, how to search () and replace with []

Stupid question, but I don’t know how to find (2000)in the regex and replace it with[2000]

+3
source share
4 answers

You can do:

str.replace(/\((\d+)\)/g, "[$1]");

Used expression: \((\d+)\)

  • (and )are special char in regex used to group to match literals ( ), you need to avoid them as \( \)
  • \dis short for numbers. \d+ means one or more digits.
  • ( )- group and remember the number. The memorized number will be used later in return.
  • gfor global replacement. I mean every appearance of the patten in the string will be replaced.
  • $1 - ( ), .
  • / / .
+12
function _foo(str) {
   return str.replace(/[(](\d*)[)]/, '[$1]');
}

alert( _foo("(2000)") );  // -> '[2000]'
alert( _foo("(30)") );    // -> '[30]'
alert( _foo("(abc)") );   // -> '(abc)'
alert( _foo("()") );      // -> '[]'
+1

Example: yourString.replace(/\(2000\)/, "[2000]");

0
source

Try the following:

function foo(S) { 
    return S.replace(/\(([^\)]+)\)/g,"[$1]");
}
0
source

Source: https://habr.com/ru/post/1763389/


All Articles