1.match () () method is essentially the same as calling the RegExp exec.
var text = "cat, bat, sat, fat"; var pattern = /.at/; //与pattern.exec(text)相同 var matches = text.match(pattern); console.log(matches.index); //0 console.log(matches.input); console.log(matches[0]); //"cat" console.log(pattern.lastIndex); //0
2.search () returns the index of the string matches the first item; -1 is not always find the scratch.
var text = "cat, bat, sat, fat", pos = text.search(/at/); console.log(pos); //1
3.replace () replacement string operation. It accepts two parameters.
a. If the first parameter is a string, then only replace the first substring. To replace all sub-strings, the only way is to provide a global flag.
var text = "cat, bat, sat, fat", result = text.replace("at", "ond"); console.log(result); //"cond, bat, sat, fat" result = text.replace(/at/g, "ond"); console.log(result); //"cond, bond, sond, fond"
b. If the second parameter is a string, it may be added some special character sequences.
var text = "cat, bat, sat, fat"; result = text.replace(/(.at)/g, "word ($1)"); console.log(result);
C. The second parameter may be a function.
- In the case of only one match, this function will be transmitted to three parameters: pattern matches, the position and pattern matches the original string in the string.
- In the case where the regular expression defines a plurality of capture groups, parameters passed to the function is still the pattern matches, the first match of a capturing group, second ......, but the last two argument is still the same.
function htmlEscape(text){ return text.replace(/[<>"&]/g, function(match, pos, originalText){ switch(match){ case "<": return "<"; case ">": return ">"; case "&": return "&"; case "\"": return """; } }) } console.log(htmlEscape("<p class=\"greeting\"> Hello world! </p>")); //<p class="greeting"> Hello world! </p>
4. split () This method can be based on the designated delimiter string into a plurality of sub-strings, and the results in an array. The separator can be a string, or may be a RegExp object.
var colorText = "red, biue, green, yellow"; var colors1 = colorText.split(","); var colors2 = colorText.split(",","2"); var colors3 = colorText.split(/[^\,]+/); console.log(colors1); //["red", " biue", " green", " yellow"] console.log(colors2); //["red", " biue"] console.log(colors3); //["", ",", ",", ",", ""] /[^\,]+/ 表示不是逗号的连续字符