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]
1 Answer 1
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]"