tags:

views:

60

answers:

2

http://stackoverflow.com/questions/2243688/javascript-text-manipulation/2244002#2244002

I need to make little manipulation in the string.I need to retrieve the matched text and then replace the matched text.Something like this

Replace("@anytext@",@anytext@)

My string can have @anytext@ any where in string multiple times.

+4  A: 

This is not jQuery, but regular JavaScript

var stringy = 'bob john';

stringy = stringy.replace(/bob/g, 'mary');
alex
That handles the replacing it, not the retrieving it.
T.J. Crowder
@T.J. IIRC the method returns the a string with the replaced substring. So stringy would contain a string in which the substring bob was replaced by the substring mary.
ChadNC
@ChadNC: Yes, that's right. My interpretation of the question was she(?) wanted to retrieve the substrings that matched, in addition to the string with the replacements having been made. But that could have been just my interpretation.
T.J. Crowder
@T.J. After re-reading the question it's obvious that I didn't read it carefully enough and that your interpretation is correct.
ChadNC
Thanks @T.J. and @ChadNC for your answers.I was exactly looking for that @T.J. has suggested.
Dee
A: 

You can make the second argument to replace a function:

str = "testing one two three";
str = str.replace(/one/g, function(match) {

    return match.toUpperCase();
});

That replaces the "one" with "ONE". The first argument to the function is the matched result from the regex. The return value of the function is what to replace the match with.

If you have any capturing groups in your regex, they'll be additional arguments to the function:

str = "testing one two three";
str = str.replace(/(on)(e)/g, function(match, group0, group1) {

    return match.toUpperCase();
});

That does exactly what the first one does, but if you wanted to, you could see what was in the capturing groups. In that example, group0 would be "on" and group1 would be "e".

T.J. Crowder