发布时间:2022-11-19 文章分类:WEB开发 投稿人:樱花 字号: 默认 | | 超大 打印

概要

在前端开发过程中,字符串的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一样的效果。

上面三段代码的执行结果是一样的,具体如下:

Javascript中replace方法与正则表达式的结合使用教程

Mustache插值

我们将下面文字中的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方法与正则表达式的结合使用教程

总结

到此这篇关于Javascript中replace方法与正则表达式结合使用的文章就介绍到这了,更多相关jsreplace与正则结合使用内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!