skij
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]'
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]') );
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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]';
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?
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes, I see I left out the 3rd set of ( )
ASKER
It works!
Open in new window