The .replace() method does change the string in place

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?


Solution 1:

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

Solution 2:

You need to save the variable after it has been replaced

valr = valr.replace('r','t'); 

Solution 3:

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');