本文共 1902 字,大约阅读时间需要 6 分钟。
字符串的replace方法
Finds the first occurrence of str1
in the current string and replaces it with str2
.
查找当前字符串中第一个出现的str1
并将其替换为str2
。
Returns a new string without mutating the original one.
返回一个新字符串,而不改变原始字符串。
'JavaScript'.replace('Java', 'Type') //'TypeScript'
You can pass a as the first argument:
您可以将作为第一个参数传递:
'JavaScript'.replace(/Java/, 'Type') //'TypeScript'
replace()
will only replace the first occurrence, unless you use a regex as the search string, and you specify the global (/g
) option:
除非您使用正则表达式作为搜索字符串,并且指定了全局( /g
)选项,否则replace()
将仅替换第一个匹配项:
'JavaScript JavaX'.replace(/Java/g, 'Type') //'TypeScript TypeX'
The second parameter can be a function. This function will be invoked when the match is found (or for every match foundm if using a global regex /g
), with a number of arguments:
第二个参数可以是一个函数。 找到匹配项(或使用全局正则表达式/g
每个匹配项发现)时,将使用以下参数调用此函数:
The return value of the function will replace the matched part of the string.
函数的返回值将替换字符串的匹配部分。
Example:
例:
'JavaScript'.replace(/Java/, (match, index, originalString) => { console.log(match, index, originalString) return 'Test'}) //TestScript
This also works for regular strings, not just regexes:
这也适用于常规字符串,而不仅仅是正则表达式:
'JavaScript'.replace('Java', (match, index, originalString) => { console.log(match, index, originalString) return 'Test'}) //TestScript
In case your regex has capturing groups, those values will be passed as arguments right after the match parameter:
如果您的正则表达式具有捕获组 ,则这些值将在match参数之后作为参数传递:
'2015-01-02'.replace(/(?\d{4})-(? \d{2})-(? \d{2})/, (match, year, month, day, index, originalString) => { console.log(match, year, month, day, index, originalString) return 'Test'}) //Test
翻译自:
字符串的replace方法
转载地址:http://paqgb.baihongyu.com/