3

This one seems simple, but I have no idea why it's not working. I would like to replace part of a string in a variable.

Say, I have this code:

var url = "At vero eos et accusam et justo duo dolores et ea rebum.";
url.replace('At vero eos et accusam et ', '');

Why doesn't it work? This one works:

var url = "At vero eos et accusam et justo duo dolores et ea rebum.".replace('At vero eos et accusam et ', ''):

-- but I'm using the variable elsewhere, so I would like to keep the replace out of the variable definition.

Fiddle here.

1
  • because .replace() is not changing the string itself it is returning a new string: jsfiddle.net/PPgzv Commented Jan 29, 2014 at 9:42

2 Answers 2

7

You need to save the replaced string

  var url = "At vero eos et accusam et justo duo dolores et ea rebum.";
  url = url.replace('At vero eos et accusam et ', '');
//^^^^^this

DEMO

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

Comments

1

Updated FIDDLE

     var url = "At vero eos et accusam et justo duo dolores et ea rebum.";
     url=url.replace('At vero eos et accusam et ', '');
     $('#box').text(url);

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.