Skip to content

Instantly share code, notes, and snippets.

@frentsel
Last active May 24, 2018 13:30
Show Gist options
  • Save frentsel/6639512 to your computer and use it in GitHub Desktop.
Save frentsel/6639512 to your computer and use it in GitHub Desktop.
js analog PHP str_replace()
String.prototype.replaceAll = function(find, replace) {
if(typeof find === 'string')
return this.split(find).join(replace);
var str = this;
find.forEach(function(el, i){
str = str.split(el).join(replace[i]);
});
return str;
}
// Test
var str = "<a href='http://$1/$2' title='$2'>$1</a>";
console.info(str.replaceAll("$1", "site.ru"));
// <a href='http://site.ru/$2' title='$2'>site.ru</a>
console.info(str.replaceAll(["$1", "$2"], ["site.ru", "big-title"]));
// <a href='http://site.ru/big-title' title='big-title'>site.ru</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment