Replace a token by another in a stringTag(s): Language


Using split() + join ()
The general pattern is str.split(search).join(replacement)
var source;
var target;

source = "Real's HowTo";
target = source.split("HowTo").join("How-To");

alert(target); // output Real's How-To

Using Regular expression
Regular expression is ok but you must take special precaution to escape some characters before because they have special meaning when used in regular expression.
function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

var source;
var target;

source = "Real's HowTo";
target = replaceAll(source, "HowTo", "How-To");

alert(target); // output Real's How-To

Using recursion
function replaceAll(s, t, u) {
  /*
  **  Replace a token in a string
  **    s  string to be processed
  **    t  token to be found and removed
  **    u  token to be inserted
  **  returns new String
  */
  i = s.indexOf(t);
  r = "";
  if (i == -1) return s;
  r += s.substring(0,i) + u;
  if ( i + t.length < s.length)
    r += replaceAll(s.substring(i + t.length, s.length), t, u);
  return r;
}

var source;
var target;

source = "Real's HowTo";
target = replaceAll(source, "HowTo", "How-To");

alert(target); // output Real's How-To

blog comments powered by Disqus