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?

Answers:

Answer

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

Answer

You need to save the variable after it has been replaced

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.