Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  2] [ 3]  / answers: 1 / hits: 166361  / 11 Years ago, thu, january 16, 2014, 12:00:00
var variableABC = "A B C"; 
variableABC.replace("B", "D") // Wanted output: "A D C".

but variableABC didn’t change:


console.log(variableABC); // "A B C"

I want it to be "A D C".


More From » string

 Answers
8

According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.



You can always just set the string to the modified value:



variableABC = variableABC.replace('B', 'D')



Edit: The code given above is to only replace the first occurrence.



To replace all occurrences, you could do:



 variableABC = variableABC.replace(/B/g, D);  


To replace all occurrences and ignore casing



 variableABC = variableABC.replace(/B/gi, D);  

[#73130] Wednesday, January 15, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mackennamelissac

Total Points: 110
Total Questions: 118
Total Answers: 103

Location: Sweden
Member since Sun, Jan 16, 2022
2 Years ago
;