正则表达式笔记(三)

String.replace

细心的读者可能会发现,上篇文章咱们遗漏了 String.replace 这个方法。String.replace 在 JS 中有着更增强大的用法和灵活性,因此这里剥离出来单独介绍。正则表达式

API

String.replace(searchValue, replacement)

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

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

参数说明

  • 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 也一块儿替换,这个时候就须要用到正则表达式。io

正则表达式替换console

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

'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 字符串中,还有一些特殊的变量能够使用。function

特殊变量 说明
$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

相关文章
相关标签/搜索