Last active
May 31, 2016 15:26
-
-
Save marcusshepp/b2bdda39ce7a690a5c61b5a5a7f19c6d to your computer and use it in GitHub Desktop.
Javascript search and replace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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