replace 正则

为了简化替换字符串的操作,ECMScript提供了replace()方法,这个方法提供两个参数,第一个参数可以使一个字符串或RegExp对象,第二个参数可以是一个字符串或者一个函数。

基础知识

$& 匹配整个模式的子字符串。与RegExp.lastMatch的值相同

$' 匹配的子字符串之前的字符串,与RegExp.leftContext的值相同

$` 匹配的子字符串之后的字符串,与RegExp.rightContext的值相同

$n 匹配第n个捕获组的子字符串,其中n等于0·9,例如$1是匹配的第一个捕获组的子字符串,$2是匹配的第二个捕获组的子字符串

如果第一个参数是字符串,那么它只会替换第一个字符串,想要替换所有字符串,唯一办法就是提供一个正则表达式,而且要指定全局(g)标志。

1.基础用法,第一个参数为字符串

  1.  
    var str="cat bat fat";
  2.  
    var result=str.replace("at","ond");
  3.  
    console.log(result); //cond bat fat

2.第一个参数为RegExp对象

  1.  
    var str="cat bat fat";
  2.  
    var result=str.replace(/at/g,"ond");
  3.  
    console.log(result);//cond bond fond

3.颠倒

  1.  
    var str="ouyang,zhaoyu";
  2.  
    var result=str.replace(/(\w+),(\w+)/,"$2,$1");
  3.  
    console.log(result);//zhaoyu,ouyang

4.与正则表达式匹配的全文本

  1.  
    var str="ouyang,zhaoyu";
  2.  
    var result=str.replace(/(\w+)/,"$&-$&");
  3.  
    console.log(result);//ouyang-zhaoyu

5.匹配匹配字符串的右边字符

    1.  
      var str="ouyang";
    2.  
      var result=str.replace(/ou/,"$'");
    3.  
      console.log(result);//yangyang

猜你喜欢

转载自www.cnblogs.com/yuanyuan-1994/p/9243773.html