zoukankan      html  css  js  c++  java
  • 浅谈JavaScript的字符串的replace方法

      JavaScript字符串提供了一个replace方法。replace方法可以接受两个参数:第一个参数可以使RegExp对象或者一个字符串,第二个参数可以是一个字符串或者一个函数。如果第一个参数是字符串,那么只会替换第一个字符串。如果想替换所有的字符串,则必须使用正则表达式。

    1 var str="hello world";
    2 var str1=str.replace("o","h");
    3 console.log(str1);//hellh world

      第一行代码定义了一个字符串变量,并初始化,第二行代码使用replace方法,将字符串中的o替换为h,从结果来看使用字符串替换,只能替换第一个字符串。

    1 var str="hello world";
    2 var str1=str.replace(/o/g,"h");
    3 console.log(str1);//hellh whrld

      上面的代码使用了正则表达式来传递参数,正则表达式会匹配所有的字符串,并替换掉。

      

    1 var str="hello world";
    2 var str1=str.replace(/o/g,function(match,pos,orginText){
    3         console.log(pos);
    4         return "a";
    5 });
    6 console.log(str1);//hella warld

      上面的代码,第一行定义了字符串变量,并初始化。第二行调用了字符串的replace方法,第一个参数是模式匹配,第二个参数是一个函数。函数拥有三个参数:第一个参数是匹配到的字符串,第二个参数是匹配的位置,第三个参数是原字符串。在函数里面可以对字符串进行操作。使用函数作为第二个参数,可以做一些复杂的替换,比如当匹配多个字符时候,可以对不同的字符做不同的替换。

     1     var str="hello world";
     2                 var str1=str.replace(/[ol]/g,function(match,pos,orginText){
     3                     console.log(pos);
     4                     if(match=="o"){
     5                         return "a";
     6                     }
     7                     else {
     8                         return "b";
     9                     }
    10                     
    11                 });
    12                 console.log(str1);//hebba warbd

    上面的代码模式匹配所有的字符o或者字符l,并在函数中进行操作。将字符o替换为a,字符l替换为b

  • 相关阅读:
    day22 Python shelve模块
    day22 Python pickle模块
    day22 Python sys模块
    day22 Python os模块
    day22 Python random模块
    day22 Python 时间模块
    day21 Python 实现的深度优先搜索实现迷宫算法
    day21 Go 实现的深度优先搜索实现迷宫算法
    杂篇
    杂篇
  • 原文地址:https://www.cnblogs.com/ggz19/p/8192265.html
Copyright © 2011-2022 走看看