views:

79

answers:

4

Silly question, but I do not know how to find (2000) into a regular expression and replace it with [2000]

A: 

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

RC
Since this is JavaScript, you may want the `/g` flag.
Kobi
+10  A: 

You can do:

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

Regex used: \((\d+)\)

  • ( and ) are special char in regex used for grouping, to match literal ( ), you need to escape them as \( \)
  • \d is short for a digit. \d+ means one or more digits.
  • ( ) is to group and remember the number. The remembered number will later be used in replacement.
  • g for global replacement. Mean every occurrence of the patten in the string will be replaced.
  • $1 is the number between ( )that was grouped and remembered.
  • / / are the regex delimiters.
codaddict
If you want to precise about the number of digits matched, you can add "counters". So you can use \d{3} to only have 3 digits, or \d{2,4} to match anything that's 2 to 4 digits. I've always found this site to be a good, easy to understand reference: http://www.regular-expressions.info/reference.html
jlindenbaum
A: 
function _foo(str) {
   return str.replace(/[(](\d*)[)]/, '[$1]');
}

alert( _foo("(2000)") );  // -> '[2000]'
alert( _foo("(30)") );    // -> '[30]'
alert( _foo("(abc)") );   // -> '(abc)'
alert( _foo("()") );      // -> '[]'
Yanick Rochon
A: 

Try this:

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