Skip to content

Instantly share code, notes, and snippets.

@marcusshepp
Last active May 31, 2016 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcusshepp/b2bdda39ce7a690a5c61b5a5a7f19c6d to your computer and use it in GitHub Desktop.
Save marcusshepp/b2bdda39ce7a690a5c61b5a5a7f19c6d to your computer and use it in GitHub Desktop.
Javascript search and replace
var s = "marcus is the king";
undefined
// the `g` flag causes multiple replacements
var soo = s.replace(/marcus/g, "foo");
undefined
soo
"foo is the king"
var foo = s.replace(/s/g, "foo");
undefined
foo
"marcufoo ifoo the king"
var bar = s.replace(/s/, "foo");
undefined
bar
"marcufoo is the king"
// with a variable
var KEYWORDS = {
"foo": "bar",
}
for(var keyword in KEYWORDS){
if (text.indexOf(keyword) > -1){
var re = new RegExp(keyword, "g");
text.replace(re, KEYWORDS[keyword]);
console.log("there it is");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment