marcus-s
5/31/2016 - 2:30 PM

Javascript search and replace

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");
  }
}