简体   繁体   English

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

[英]Javascript : replace string at specific position

I have a String like that : 我有一个像这样的字符串:

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

I would like to replace "12345" by "****". 我想将“ 12345”替换为“ ****”。

The script must take into account the fact that the string containing between and is never the same. 该脚本必须考虑到包含在和之间字符串永远不相同的事实

You can use this regex: 您可以使用此正则表达式:

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

If you don't want lookahead then use capturing groups on both sides: 如果您不希望超前,请在两侧使用捕获组:

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

If digits won't always be wrapped between a <test> tag, here's another way to solve the same problem. 如果数字不一定总是被包含在<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"

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

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