General use
var str = "Test-test-test"= "Test-test-test". Replace ("Test", "OK"); Console.log (str);
Use the Regular:
var str = "Test-test-test"= "Test-test-test". Replace (/test/g, "OK"); Console.log (str);
Loop Replace
In this case, the substitution of emoticons, we need a normal string substitution, for example with the while + INDEXOF implementation.
varfaces = { "/::)": "Weixiao", "/::~": "Pizui", "/::b": "Se", "/::|": "Fadai", "/:8-"): "Deyi", "/::<": "Liulei", "/::$": "Haixiu", "/:: ' (": "Daku", "/::-|": "Gangga"};varstr = "/::)-/::b-/::)-/:8-)-/:8-)"; for(varKinchfaces) { while(Str.indexof (k) >-1) {str=str.replace (k, faces[k]); }}console.log (str);
In this way, the basic skills can be achieved, but this is problematic, if there is a key value of the same, it will die loop for example:
var faces = { "/::)": "Weixiao", "/:hehe": "/:hehe"}; var str = "/::)-/::b-/:hehe-/:8-)-/:8-)"; for (var in faces) { while (Str.indexof (k) >-1) { = str.replace (k, faces[k]);} } Console.log (str);
Modify the following code to resolve the dead loop problem:
varfaces = { "/::)": "Weixiao", "/:hehe": "/:hehe"};varstr = "/::)-/::b-/:hehe-/:8-)-/:8-)"; for(varKinchfaces) { varp =-1;//where characters appear vars = 0;//Next start position while(P = Str.indexof (k, s)) >-1) {s= p + faces[k].length;//position + length of valuestr =str.replace (k, faces[k]); }}console.log (str);
Then simply encapsulate:
/** * String substitution * @param {string} str to be replaced by String * @param {string} substr string to replace * @param {string} newstr string to replace * @r Eturn the new string after the {string} substitution*/functionreplace (str, substr, newstr) {varp =-1;//where characters appear vars = 0;//Next start position while(P = str.indexof (substr, s)) >-1) {s= p + newstr.length;//position + length of valuestr =str.replace (substr, NEWSTR); } returnstr;} Console.log (replace ("Ssssss", "SS", "S"));//SSS
Using the RegExp Package
/* * * string substitution * @param {string} str string to be replaced * @ param {String} substr the string to replace * @param {string} newstr the string to replace * @return {string} after the replacement of the new string */ function replace (str, substr, NEWSTR {substr = Substr.replace (/[.\\[\]{} () |^$?*+]/g, "\\$&"); // metacharacters in the escaped string var re = new RegExp (substr, "G"); // generate regular return Str.replace (re, NEWSTR);} Console.log (replace ( "Ssssss", "SS", "S")); // SSS
Reference Address: http://www.52cik.com/2015/11/06/replace-all.html
JS Basic article--replace Replace all the correct application