1

The Problem

I'm trying to use the JavaScript string replace method to replace some text in a div if it contains a certain string. However, my code does not replace the string inside that div.

The Javascript

function john(){
  var NAME = "Johnny Buffet,";
  var val = $("div#like-list-").text();
  if ( val.indexOf(NAME) !== -1 ){
      val.replace(NAME, '');      
  }
}
5
  • 5
    THERE IS NO jQuery replace() function Commented Aug 12, 2013 at 5:15
  • replace is a javascript method and you need to update the text of your element, because right now you're just operating on the variable and not saving the edited string anywhere Commented Aug 12, 2013 at 5:16
  • @koala_dev: "you're just changing the variable" --- nope, that's incorrect Commented Aug 12, 2013 at 5:16
  • @zerkms fixed the wording on my comment Commented Aug 12, 2013 at 5:19
  • @Leighton: There is also the manual how to change the text of an element with jQuery: api.jquery.com/text Commented Aug 12, 2013 at 5:19

3 Answers 3

2

It doesn't work because .replace() is a String function and not a jQuery function; Strings in JavaScript are immutable, so .replac() returns the modified String which you then have to reassign to your element.

That said, you can use .text(fn) to perform the replacement in a single step:

$("div#like-list-").text(function(i, val) {
    return val.replace(NAME, '');
});

Btw, I've removed the .indexOf() condition as well, because if NAME doesn't occur inside your string, the .replace() function will just return the original string.

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

Comments

1

You're editing the string, then simply throwing it away. Take the edited val and put it's contents back into the HTML element using a parameterized call to the text method.

function john(){
  var NAME = "Johnny Buffet,";
  var val = $("div#like-list-").text();
  if ( val.indexOf(NAME) !== -1 ){
      $("div#like-list-").text(val.replace(NAME, ''));
  }
}

1 Comment

@Leighton You're welcome, though @Jack's answer is probably a cleaner approach. If any of these answers solves your problem, remember to mark it as accepted by clicking the check mark next to it.
0

replace() is javascript not jQuery and you need to reset the value to variable after replace as replace() returns the updated text; ie;

val = val.replace(NAME, '');      

so try:

function john(){
  var NAME = "Johnny Buffet,";
  var val = $("div#like-list-").text();
  if ( val.indexOf(NAME) !== -1 ){
     val = val.replace(NAME, '');      
  }
}

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.