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:
2+22(2+2)
into 2+22*(2+2)
, -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:
'2+2(2+2)'.replace(/([0-9])\(/g, '$1*(')
'2+2(2+2)'.replace(/(\d)\(/g, '$1*(') //Another option: [0-9] = \d
Suggestion : 2.
is often a valid number (= 2
). The following RegExp removes a dot between a number and a parenthesis.
'2+2(2+2)'.replace(/(\d\).?\(/g, '$1*(') //2.(2+2) = 2*(2+2)
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.
var str = '2+2(2+2)+3(1+2)+2(-1/2)'.replace(/([0-9])\(/g, '$1*(');
This follows what you wrote (the bracket must follow a number).
So 4(
will be changed to 4*(
it could be important for example for 4(-1/2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.