1

I simply try to use the .replace() method. And it does not work.

HTML:

<div class="try"> </div>

JS:

var valr='r';
valr.replace('r', 't');
$('.try').prepend('<div> ' + valr + '</div>');

Result: I get 'r', while I would like to get 't'

Any idea on why it doesn't work?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Juliette Dupuis
  • 1,027
  • 2
  • 13
  • 22
  • From the [MDN docs](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace) _This method does not change the String object it is called on. It simply returns a new string._ – epascarello Nov 20 '12 at 14:47

3 Answers3

14

replace() (a JavaScript function, not jQuery) returns a string, try this :

var valr='r';
valr = valr.replace('r', 't');
$('.try').prepend('<div> '+valr+'</div>');

Docs for .replace() are here

Manse
  • 37,765
  • 10
  • 83
  • 108
  • @JulietteDupuis no probs - check out the [MDN](https://developer.mozilla.org/en-US/docs/JavaScript/Reference) when you have issues like this - all JavaScript functions are documented there – Manse Nov 20 '12 at 14:45
7

You need to save the variable after it has been replaced

valr = valr.replace('r','t'); 
Anton
  • 32,245
  • 5
  • 44
  • 54
5

First off replace is not a jQuery method - it's plain javascript. Second, it returns a new instance of the string so you need:

valr = valr.replace('r', 't');
Jamiec
  • 133,658
  • 13
  • 134
  • 193