JS利用正则表达式替换字符串中的内容

  //从字符串'Is this a cat is'中剪去'is':
  var str='Is this a cat is';

  var subStr=new RegExp('is');//创建正则表达式对象
  var result=str.replace(subStr,"");//把'is'替换为空字符串
  console.log(result);//Is th a cat is

  var subStr=new RegExp('is','i');//创建正则表达式对象,不区分大小写
  var result=str.replace(subStr,"");//把'is'替换为空字符串
  console.log(result);//this a cat is
    
  var subStr=new RegExp('is','ig');//创建正则表达式对象,不区分大小写,全局查找
  var result=str.replace(subStr,"");//把'is'替换为空字符串
  console.log(result);//th a cat

  var subStr=/is/ig;//直接量法创建正则表达式对象,不区分大小写,全局查找
  var result=str.replace(subStr,"");//把'is'替换为空字符串
  console.log(result);//th a cat

  console.log(str);//Is this a cat is 可见replace并不改变原始str

posted on 2020-05-31 11:07  被窝暖暖嘻嘻嘻  阅读(1442)  评论(0编辑  收藏  举报

导航