Silly question, but I do not know how to find (2000)
into a regular expression and replace it with [2000]
views:
79answers:
4Since this is JavaScript, you may want the `/g` flag.
Kobi
2010-09-06 04:20:52
+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
2010-09-06 04:19:46
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
2010-09-06 04:31:46
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
2010-09-06 04:20:29