SolutionCottage.com
Posted  05 Nov 2008 - 08:57:15

Category: JavaScript


variable not changed when using javascript replace function

Issue:
You might want to use the JavaScript replace function to replace characters in a string like this:

var str = "This is a text.";
str.replace(/ /g, "_");
alert(str);


You notice that the old string is used in the alert function.

Solution:
This is not the correct way of using replace, you are not altering the string by invoking the shared function. Use this method to get the new string:

var str = "This is a text.";
var newStr = str.replace(/ /g, "_");
alert(newStr);








0 comments:








© SolutionCottage 2008-2011 7/21/2017 3:37:19 AM