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

LVL 10
skijAsked:
Who is Participating?
 
skijConnect With a Mentor Author Commented:
Thank you.  Julian, I made a slight adjustment because your code wasn't quite producing the expected results.  

This works:
str.replace(/(\[\d+\])(.*?)(\[\d+\])(.*?)\[\d+\]/, '$1$2$3$4[X]')

Open in new window

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

Open in new window

0
 
Kim WalkerConnect With a Mentor Web Programmer/TechnicianCommented:
You're going to have to be a little more specific. Search for the first two bracketed numbers literally and include them in the replace with a callback.
var str = 'hello[11][22][33][44][55]';
alert( str.replace(/(\[[0-9]+\]\[[0-9]+\])\[[0-9]+\]/, '$1[X]')  );

Open in new window

0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
skijAuthor Commented:
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

0
 
Kim WalkerWeb Programmer/TechnicianCommented:
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?
0
 
skijAuthor Commented:
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!
0
 
Julian HansenConnect With a Mentor Commented:
Try this
str.replace(/(\[\d+\])(.*?)\[\d+\](.*?)(\[\d+\])/, '$1$2$3$4[X]') ;

Open in new window

0
 
Julian HansenCommented:
Yes, I see I left out the 3rd set of (  )
0
 
skijAuthor Commented:
It works!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.