Monday, July 08, 2013

JavaScript replaceAll Example

I needed a JavaScript "replaceAll" function on a string. Note the global flag /g
var name = "John Jacob Jingleheimer Smith";
//replace the space with a dot '.'
var id = name.replace(/\s/g, '.');
console.log(id);
//now replace the '.' with a space
newId = id.replace(/\./g, ' ');
console.log(newId);
view raw replaceAll.js hosted with ❤ by GitHub
The output is:
John.Jacob.Jingleheimer.Smith
John Jacob Jingleheimer Smith

No comments: