javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > js replace与正则结合使用

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

作者:懒人Ethan

replace方法是javascript涉及到正则表达式中较为复杂的一个方法,严格上说应该是string对象的方法,下面这篇文章主要给大家介绍了关于Javascript中replace方法与正则表达式的结合使用的相关资料,需要的朋友可以参考下

概要

在前端开发过程中,字符串的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插值

我们将下面文字中的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与正则结合使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文