开发者

string manipulation in JavaScript: retrieve the matched text and then replace the matched text

开发者 https://www.devze.com 2022-12-19 17:32 出处:网络
JavaScript text manipulation I need to make little manipulation in the string. I need to retrieve the 开发者_JAVA百科matched text and then replace the matched text. Something like this

JavaScript text manipulation

I need to make little manipulation in the string. I need to retrieve the 开发者_JAVA百科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.


This is not jQuery, but regular JavaScript

var stringy = 'bob john';

stringy = stringy.replace(/bob/g, 'mary');


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".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号