博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
字符串的replace方法_字符串replace()方法
阅读量:2502 次
发布时间:2019-05-11

本文共 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 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(/(?
\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/

你可能感兴趣的文章
利用正则表达式群发定制邮件
查看>>
【原】RDD专题
查看>>
第三周——构建一个简单的Linux系统MenuOS
查看>>
Docker 的两类存储资源 - 每天5分钟玩转 Docker 容器技术(38)
查看>>
Codeforces 257D
查看>>
常用的20个强大的 Sublime Text 插件
查看>>
ajaxfileupload.js在IE中的支持问题
查看>>
tensorflow学习之(十)使用卷积神经网络(CNN)分类手写数字0-9
查看>>
当document.write里含有script标签时
查看>>
工作中常见问题
查看>>
JAVA 从一个List里删除包含另一个List的数据
查看>>
外国的月亮比较圆吗?外籍团队工作有感
查看>>
CentOS 关闭烦人的屏保
查看>>
分布式系统事务一致性解决方案
查看>>
ShuffleNet总结
查看>>
前后台验证字符串长度
查看>>
《算法导论 - 思考题》7-1 Hoare划分的正确性
查看>>
IOS 简单的动画自定义方法(旋转、移动、闪烁等)
查看>>
图像处理笔记(十二)
查看>>
Chapter 3 Phenomenon——9
查看>>