博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
正则表达式笔记(三)
阅读量:7085 次
发布时间:2019-06-28

本文共 1974 字,大约阅读时间需要 6 分钟。

String.replace

细心的读者可能会发现,上篇文章我们遗漏了 String.replace 这个方法。String.replace 在 JS 中有着更加强大的用法和灵活性,所以这里剥离出来单独介绍。

API

String.replace(searchValue, replacement)

String.replace 同时支持进行正则表达式或者字符串替换,并返回一个新的字符串。因为我们的主题是正则表达式,所以接下来的内容,会以正则替换的情况为主。

默认情况下,String.replace只进行一次替换。若设置了 g 模式,则所有匹配到的字符串都会替换

参数说明

  • String: 需要替换的字符串
  • searchValue: 字符串或者正则表达式
  • replacement: 字符串或者函数

用法

字符串替换

'I am back end developer'.replace('back','front');//"I am front end developer"

直接把字符串中的 back 替换成 front。当字符串中有两个 back,情况回事怎样呢?

'I am back end developer, you are back end developer'.replace('back','front');//"I am front end developer, you are back end developer"

可以看到,第2个 back,并没有被替换。如果需要把其他 back 也一起替换,这个时候就需要用到正则表达式。

正则表达式替换

设置了 g 模式,全局替换。

'I am back end developer, you are back end developer'.replace(/back/g,'front');//"I am front end developer, you are front end developer"

replacement 字符串中,还有一些特殊的变量可以使用。

特殊变量 说明
$1,$2,$3...$n 表示对应捕获分组匹配的文本
$& 与正则相匹配的字符串
$$ '$' 字符
$` 匹配字符串左边的字符
$' 匹配字符串右边的字符

有趣的字符串替换

使用 $& 操作匹配的字符串。

var str = '有趣的字符串替换';str.replace(/有趣的字符串/,'($&)');//"(有趣的字符串)替换"

使用 $$ 声明 $ 字符。

var str = '这个商品的价格是12.99';str.replace(/\d+\.\d{2}/,'$$$&');//"这个商品的价格是$12.99"

使用 $` 和 $' 字符替换内容

'abc'.replace(/b/,"$`");//aac'abc'.replace(/b/,"$'");//acc

使用分组匹配组合新的字符串

'2015-05-06'.replace(/(\d{4})-(\d{2})-(\d{2})/,"$3/$2/$1")//"06/05/2015"

函数参数

replacement是一个函数参数的时候,对字符串操作的灵活性将有一个质的提高。

说明

'Stirng.replace'.replace(/(\w+)(\.)(\w+)/,function(){    console.log(arguments) // ["Stirng.replace", "Stirng", ".", "replace", 0, "Stirng.replace"]    return '返回值会替换掉匹配到的字符'})
参数 说明
match 匹配到的字符串(此例为 String.replace)
p1, p2, ... 正则使用了分组匹配时分组文本,否则无此参数(此例为 "Stirng", ".", "replace")
offset 匹配字符串的对应索引位置 (此例为 0)
source 原始字符串(此例为 String.replace)

案例 -- 样式属性的转换

把驼峰字符转换为 - 连接符形式

'borderTop'.replace(/[A-Z]/g,function(m){    return '-'+ m.toLowerCase()})//"border-top"

- 连接符形式转换为驼峰形式

'border-top'.replace(/-(\w)/g,function(m,s){    return s.toUpperCase()})//"borderTop"

最后的牛刀小试

交给阅读者发挥的内容:

需要将Hello-World使用正则替换成 HWeolrllod

转载地址:http://odwql.baihongyu.com/

你可能感兴趣的文章