简体   繁体   English

JavaScript中的字符串处理:检索匹配的文本,然后替换匹配的文本

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

JavaScript text manipulation JavaScript文字处理

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@) 替换(“ @anytext @”,@ anytext @)

My string can have @anytext@ any where in string multiple times. 我的字符串可以在字符串中的任意位置多次使用@ anytext @。

This is not jQuery, but regular JavaScript 这不是jQuery,而是常规JavaScript

var stringy = 'bob john';

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

You can make the second argument to replace a function: 您可以使用第二个参数来replace函数:

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". 在该示例中, group0将为“ on”,而group1将为“ e”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM