Javascript:在特定位置替换字符串

时间:2014-05-27 19:37:53

标签: javascript regex replace

我有一个像这样的字符串:

var str = "Hello, it is a <test>12345</test> and it's fun";

我想替换&#34; 12345&#34; by&#34; ****&#34;。

脚本必须考虑到字符串包含介于两者之间并且永远不会相同的事实。

2 个答案:

答案 0 :(得分:4)

您可以使用此正则表达式:

str = str.replace(/(<test>).*?(?=<\/test>)/, '$1*****');
//=> "Hello, it is a <test>*****</test> and it's fun"

如果您不想要前瞻,那么请在两侧使用捕获组:

str = str.replace(/(<test>).*?(<\/test>)/, '$1*****$2');
//=> "Hello, it is a <test>*****</test> and it's fun"

答案 1 :(得分:1)

如果数字不会总是包含在<test>标记之间,那么这是另一种解决同一问题的方法。

var str = "Hello, it is a <test>12345</test> and it's fun";

var numberPattern = /(\<\w+\>)(\d+)(\<\/\w+\>)/gi;

str = str.replace(numberPattern, "$1****$3");

// str is now "Hello, it is a <test>****</test> and it's fun"