1

I'm making a script that reads a .txt file and puts it into a variable which looks like:

myString = "blablabla [12], foo bar bar[2], bar foo[34], hello hello [95], wheres my sandwich [2745]";

I managed to generate an array that contains all the values between brackets, to do so I used this line of code:parameters = myString.match(/[^[]+(?=\])/g);

So now I can easily get any of those values by calling parameters[n]

All I want to do now is to change the value of one of those elements between [ ], and inject it back to the string, but I don't know how to do it. Of course if I use the following line:

myString = myString.replace(/[^[]+(?=\])/g, "newValue");

All the elements will be replaced so I will end up with a string like blablabla [newValue], foo bar bar[newValue], bar foo[newValue], hello hello [newValue], wheres my sandwich [newValue]

asked Jan 18, 2014 at 13:09

1 Answer 1

3

String.prototype.replace accepts not only string, but also function as replacement. If you pass a function, the return value of the function is used as replacement string.

Using that feature:

var nth = 0;
myString.replace(/[^[]+(?=\])/g, function(match) {
 // Change only the 2nd matched string.
 return ++nth == 2 ? "newValue" : match;
});
// => "blablabla [12], foo bar bar[newValue], bar foo[34], hello hello [95],
// wheres my sandwich [2745]"
answered Jan 18, 2014 at 13:16

1 Comment

you are just fantastic! thank you very much for the help.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.