JS basic part -- replace all correct applications

General use

var str = "test-test-test";
str = "test-test-test".replace("test", "ok");
console.log(str);

Use regular:

var str = "test-test-test";
str = "test-test-test".replace(/test/g, "ok");
console.log(str);

Loop replacement

In the following case, we need to replace the emoticon tag with normal string replacement, such as while + indexOf.

var faces = {
  "/::)": "weixiao",
  "/::~": "pizui",
  "/::B": "se",
  "/::|": "fadai",
  "/:8-)": "deyi",
  "/::<":"liulei",
  "/::$": "haixiu",
  "/::'(": "daku",
  "/::-|": "gangga"
};

var str = "/::)-/::B-/::)-/:8-)-/:8-)";

for (var k in faces) {
  while(str.indexOf(k) > -1) {
    str = str.replace(k, faces[k]);
  }
}

console.log(str);

In this way, the basic function is implemented, but there is a problem. If there is a key with the same value, it will be in a dead cycle, for example:

var faces = {
  "/::)": "weixiao",
  "/:hehe": "/:hehe"
};

var str = "/::)-/::B-/:hehe-/:8-)-/:8-)";

for (var k in faces) {
  while(str.indexOf(k) > -1) {
    str = str.replace(k, faces[k]);
  }
}

console.log(str);

Modify to the following code to solve the problem of dead cycle:

var faces = {
  "/::)": "weixiao",
  "/:hehe": "/:hehe"
};

var str = "/::)-/::B-/:hehe-/:8-)-/:8-)";

for (var k in faces) {
  var p = -1; // Character position
  var s = 0; // Next start position
  while((p = str.indexOf(k, s)) > -1) {
    s = p + faces[k].length; // Length of position + value
    str = str.replace(k, faces[k]);
  }
}

console.log(str);

Let's do a simple encapsulation:

/**
 * String substitution
 * @param  {string} str    String to be replaced
 * @param  {string} substr String to replace
 * @param  {string} newstr String to replace
 * @return {string}        New string after replacement
 */
function replace(str, substr, newstr) {
  var p = -1; // Character position
  var s = 0; // Next start position

  while((p = str.indexOf(substr, s)) > -1) {
    s = p + newstr.length; // Length of position + value
    str = str.replace(substr, newstr);
  }

  return str;
}

console.log( replace("ssssss", "ss", "s") ); // sss

Using regular expression encapsulation

/**
 * String substitution
 * @param  {string} str    String to be replaced
 * @param  {string} substr String to replace
 * @param  {string} newstr String to replace
 * @return {string}        New string after replacement
 */
function replace(str, substr, newstr) {
  substr = substr.replace(/[.\\[\]{}()|^$?*+]/g, "\\$&"); // Metacharacters in escape strings
  var re = new RegExp(substr, "g"); // Generate regular
  return str.replace(re, newstr);
}

console.log( replace("ssssss", "ss", "s") ); // sss

Source: Peking University Bluebird school Front end development team

Posted by dai.hop on Tue, 31 Mar 2020 23:56:11 -0700