标签:
Thereplace()
method returns a new string with some or all matches of apattern
replaced by areplacement
.
Thepattern
can be a string or aRegExp
, and thereplacement
can be a string or a function to be called for each match.
语法:
str.replace(regexp|substr, newSubStr|function[, flags])
regexp (pattern)
RegExp
object or literal. The match is replaced by the return value of parameter #2.substr (pattern)
String
that is to be replaced by newSubStr
. It is treated as a verbatim string and is notinterpreted as a regular expression.newSubStr (replacement)
String
that replaces the substring received from parameter #1. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.function (replacement)
var str = ‘Twas the night before Xmas...‘; var newstr = str.replace(/xmas/i, ‘Christmas‘); console.log(newstr); // Twas the night before Christmas...
例2:
var re = /apples/gi; var str = ‘Apples are round, and apples are juicy.‘; var newstr = str.replace(re, ‘oranges‘); console.log(newstr); // oranges are round, and oranges are juicy.
例3:
var re = /(\w+)\s(\w+)/; var str = ‘John Smith‘; var newstr = str.replace(re, ‘$2, $1‘); console.log(newstr); // Smith, Joh
例4:
function styleHyphenFormat(propertyName) { function upperToHyphenLower(match) { return ‘-‘ + match.toLowerCase(); } return propertyName.replace(/[A-Z]/g, upperToHyphenLower); }
例5:
function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics console.log(arguments); return [p1, p2, p3].join(‘ - ‘); } var newString = ‘abc12345#$*%aaa‘.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
标签:
原文地址:http://www.cnblogs.com/oxspirt/p/5460979.html