0

I have a String something like var someString = 'Some foo email string {{Email18}} bla bla'.

I need to search and replace a substring {{Email18}} but I don't know the digit or number part. I want to something like someString.replace("{{Email*}}", "Foo") and resultant string be like 'Some foo email string Foo bla bla'.

How can I do that?

2 Answers 2

1

Just use \d character class if at least one digit is present at the end of substring:

var someString = 'Some foo email string {{Email18}} bla bla',
    replaced = someString.replace(/{{Email\d{1,}}}/, "Foo");

console.log(replaced);  // "Some foo email string Foo bla bla"
Sign up to request clarification or add additional context in comments.

2 Comments

Can you also please tell me how I can get the substring like someString.search(/{{Email\d{1,}}}/) which will give me {{Email18}}?
@NitinAggarwal, use match method: var subStr = someString.match(/{{Email\d{1,}}}/); console.log(subStr[0]); // will give "{{Email18}}"
1

You can use a regular expression match to replace:

someString.replace(/\{\{Email\d+\}\}/, "Foo")

where you escape the brackets (operators) and have an expression for 1 or more digits (\d+).

1 Comment

Are you sure the regex is right? It is not working in my code.

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.