4

I've got a JS string

var str = '<at id="11:12345678">@robot</at> ping'; 

I need to remove this part of a string

<at id="11:12345678">@

So I am trying to use

var str = str.replace("<at.+@","");

But there is no change after excution. Moreover if I try to use match it gives me

str.match("<at.+@");
//Result from Chrome console Repl
["<at id="11:12345678">@", index: 0, input: "<at id="11:12345678">@robot</at> ping"]

So pattern actualy works but replace do nothing

4
  • 1
    Because you didn't pass in a regex! Try this: var str = str.replace(/<at.+@/,""); Commented Mar 16, 2017 at 11:19
  • Thanks! But why match works in that case? Commented Mar 16, 2017 at 11:21
  • Because match is already expecting a regex so if you provide a string it will create a regex using new RegExp. But replace could take both a string litteral or a regex. If the parametter is a string then it will not be transformed into a regex it will just look for it as a string litteral and since there is no substring "<at.+@" it will replace nothing! Commented Mar 16, 2017 at 11:33
  • Thanks a lot for detailed answer! Commented Mar 16, 2017 at 12:22

1 Answer 1

5

Use // for regex. Replace "<at.+@" with /<at.+@/.

var str = '<at id="11:12345678">@robot</at> ping'; 

str = str.replace(/<at.+@/,"");

console.log(str);

Documentation for replace

Sign up to request clarification or add additional context in comments.

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.