Javascript replace all

Javascript replace all

In Python, if you use the replace method of string, all the relevant characters are changed, but in javascript, only the first part is changed and no further progress is made.

Solution: Use a regular expression

var s = "Hello World"; 
s.replace('o','p'); 
//result : Hellp World 
s.replace(/o/g,'p'); 
//result : Hellp Wprld 

Bonus! How can we change two different characters?

Solution: Use regular expressions well.

var s = "this is java-script"; s.replace(/s/g,'').replace(/-/g,''); 
//result : thisisjavascript 
//or 
s.replace(/-|s/g,'');
Comments are closed.
%d bloggers like this: