A bit shorter but slower:
function(a,b,c,d){for(;d!=(a=a.split(b).join(c));d=a);return a}
function ( | |
a, // the string to be replaced | |
b, // a string that is to be replaced by newSubStr | |
c // the string that replaces the substring received from parameter #1 | |
) { | |
while (~a.indexOf(b)) // iterate until it doesn't contain newSubstr | |
a = a.split(b).join(c); // assign and replace all matching substr's | |
return a // return the replaced string | |
} |
function(a,b,c){while(~a.indexOf(b))a=a.split(b).join(c);return a} |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2013 Yannick Albert <http://yckart.com> | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. |
{ | |
"name": "replaceAll", | |
"description": "Replaces each substring of a string that matches the given substring with the given replacement.", | |
"keywords": [ | |
"replace", | |
"replaceAll", | |
"string", | |
"substring", | |
"loop" | |
] | |
} |
<!DOCTYPE html> | |
<title>replaceAll</title> | |
<div>Expected value: <b>Foo is not equal to bar.</b></div> | |
<div>Actual value: <b id="ret"></b></div> | |
<script> | |
var replaceAll = function(a,b,c){while(~a.indexOf(b))a=a.split(b).join(c);return a}; | |
document.getElementById('ret').innerHTML = replaceAll('Foo is not equal to bar.', ' ', ' '); | |
</script> |
Save some space by comparing with last result instead of indexOf: