简体   繁体   中英

JavaScript match ( followed by a digit

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) into 2+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:

'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*(');

http://jsfiddle.net/ZXU4Y/3/

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)

You can use capturing groups and backreferences to do it.

Check out this page , under "Replacement Text Syntax" for more details.

Here's a fiddle that does what you ask for.

Hope this helps.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM