• 1
  • 0

正则表达式替换字符串

2019-05-13 249 1 admin 所属分类:Javascript

演示代码

var str='Is this all there is';

替换单个

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

不区分大小写

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

替换全部

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


也可以用eval处理 内容高亮演示

var searchText = "haorooms";
var html = $(".Hrooms-dashb-list").html();
alert("old" + html);
var newHtml = html.replace(eval("/>(" + searchText + ")</gi"), '><em class="highlight">$1</em><');
alert("new" + newHtml);
//注释"/>("+searchText+")</gi"  “/”是正则里面的,">"是<span>中的“>”,gi是正则中的g是全部,i是部分大小写。$1是匹配括号中的内容

相关正则参数

/i (忽略大小写)
/g (全文查找出现的所有匹配字符)
/m (多行查找)
/gi(全文查找、忽略大小写)
/ig(全文查找、忽略大小写)

替换URL地址参数演示

var reg=new RegExp("(https://blog.nango.top/artilce/)(\\d+),(\\d+).html","gmi");
var url="https://blog.nango.top/artilce/1017141,20361055.html";

var rep=url.replace(reg,"$1look.html?id=$2&cid=$3");
alert(rep);
//输出 https://blog.nango.top/artilce/look.html?id=1017141&cid=20361055


返回顶部