字符串的replace方法_字符串replace()方法

字符串的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 regular expression 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 string that matches the pattern

    与模式匹配的字符串
  • an integer that specifies the position within the string where the match occurred

    一个整数,指定匹配发生在字符串中的位置
  • the string

    字符串

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(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/, (match, year, month, day, index, originalString) => {
  console.log(match, year, month, day, index, originalString)
  return 'Test'
}) //Test

翻译自: https://flaviocopes.com/javascript-string-replace/

字符串的replace方法

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值