Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

JavaScript/REGEX: Replace the 3rd match

Using JavaScript and Regular Expressions, how can I replace the third match?

For example, I want JavaScript to return this:
hello[11][22][X][44][55]'
var str = 'hello[11][22][33][44][55]';
alert( str.replace(/(\[[0-9]+\]){3}/, '[X]')  );

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

You can try
var r = str.replace(/(\[\d+\]\[\d+\])(\[\d+\])/, '$1[X]') ;

Open in new window

SOLUTION
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of skij

ASKER

Is there a way to accommodate the possibility of text between brackets in the strong?

In the example below, [33] should be replaced with [X] in both scenarios.
var str = 'hello[11][22][33][44][55]';
var str = 'hello[11][world][22][example7][33][value][44][test][55]';

Open in new window

Now [33] is not the third bracketed set of characters. It is the fifth. How do you know to replace the fifth one in this case? Or are you always replacing [33] precisely?
Avatar of skij

ASKER

I want to replace the third group of bracketed numbers.  So [123] should count but [xyz] should not.  I only want the third group of bracketed numbers.  Thanks!
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, I see I left out the 3rd set of (  )
Avatar of skij

ASKER

It works!