In string n+n(n+n), where n stands for any number or digit, I’d like to match ( and replace it by *(, but only if it is followed by a number or digit.
Examples:
- I’d like to change
2+22(2+2)into2+22*(2+2), - I’d like to change
-1(3)into-1*(3), 4+(5/6)should stay as it is.
This is what I have:
var str = '2+2(2+2)'.replace(/^[0-9]\(/g, '*(');
But it doesn’t work. Thanks in advance.
Remove the
^, and group the digits:Suggestion:
2.is often a valid number (=2). The following RegExp removes a dot between a number and a parenthesis.Parentheses create a group, which can be referenced using
$n, where n is the index of the group:$1.You started your RegExp with a
^..., which means: Match a part of the string which starts with.... This behaviour was certainly not intended.