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 "****".
The script must take into account the fact that the string containing between and is never the same.
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 "****".
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.
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"