Skip to content

Instantly share code, notes, and snippets.

@yckart
Forked from 140bytes/LICENSE.txt
Last active December 22, 2015 08:59
Show Gist options
  • Save yckart/6448865 to your computer and use it in GitHub Desktop.
Save yckart/6448865 to your computer and use it in GitHub Desktop.
replaceAll

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>
@atk
Copy link

atk commented Sep 6, 2013

Save some space by comparing with last result instead of indexOf:

function(a,b,c,d){for(;d!=(a=a.split(b).join(c));d=a);return a}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment