0

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.

1
  • Alright I think I can answer this, but are you saying that the replaced string will always be between <test> and </test>? Commented May 27, 2014 at 19:39

2 Answers 2

4

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.