目录概要replace方法基本介绍案例说明字符串关键字高亮显示Mustache插值总结概要 在前端开发过程中,字符串的replace方法在数据处理中非常常用。本文通过一个关键字高亮显
在前端开发过程中,字符串的replace方法在数据处理中非常常用。本文通过一个关键字高亮显示的实例和一个文字插值的实例,来说明replace方法如何结合正则表达式,从而更加灵活的满足各种需求。
函数参数和返回值
字符串参数
将下面加粗的文字包上
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
"The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced."
.replace(/(replace\(\)|pattern|replacement)/ig, "<span class='highlight'>$&<\/span>")
"The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced."
.replace(/(replace\(\)|pattern|replacement)/ig, "<span class='highlight'>$1<\/span>")
var str = "(replace\\(\\)|pattern|replacement)";
var reg = new RegExp(str, "gi");
"The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced."
.replace(reg, "<span class='highlight'>$1<\/span>")
本文给出了三种实现方法:
因为有些低版本浏览器并不支持replaceAll方法,所以都采用全局模式即“g”,即全文搜索,全文替换,这样可以到达和replaceAll一样的效果。
上面三段代码的执行结果是一样的,具体如下:
我们将下面文字中的Mustache内容,按照data中的key值进行替换。
var data = {
p1: "replace()",
p2: "replacement",
p3: "pattern"
};
"The {{p1}} method returns a new string with some or all matches of a pattern replaced by a {{p2}}. The {{p3}} can be a string or a RegExp, and the {{p2}} can be a string or a function called for each match. If {{p3}} is a string, only the first occurrence will be replaced."
.replace(/\{\{\s*(.*?)\s*\}\}/gi, function(str, ...args){
return data[args[0]];
});
执行结果如下:
到此这篇关于javascript中replace方法与正则表达式结合使用的文章就介绍到这了,更多相关js replace与正则结合使用内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Javascript中replace方法与正则表达式的结合使用教程
本文链接: https://www.lsjlt.com/news/168693.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0