1

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.

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I don't think the the lookahead is necessary - the OP said "only if it's being followed by number" but I think they meant "only if it follows a number"
+1 But you should be consistent with the use of [0-9] and \d
I've updated my answer, because the question has changed. The look-ahead disappeared.
NullUserException: Fixed, Rob W: That works. Thanks! (@Update: This works too, thanks).
2
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)

1 Comment

Not replied as first, but works fine (but still Rob's W solution is a bit better). Thanks.
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.

2 Comments

damnit! 8 minutes too late :(
@above: But helpful! Nice of you that you gived a fiddle, with same examples like me. Thanks ;).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.