javascript正则表达式替换,如何提供正则表达式条件(和标志)作为变量而不是内联? [英] javascript regex replace, how to provide regex condition (and flags) as variable instead of inline?

查看:102
本文介绍了javascript正则表达式替换,如何提供正则表达式条件(和标志)作为变量而不是内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将JS替换函数与regex一起使用,并将有几十个替换语句。

Using the JS replace function with regex, and will have dozens of replace statements.

var NewHTML = OriginalHTML
.replace(/\bJavaScript\b/gi, "<a href=\"http://js.com/\">$&</a>")
.replace(/\bMySQL\b/gi, "<a href=\"http://www.mysql.com/\">$&</a>")
;

使其更具可读性和可管理性(即通过更改它更容易更改正则表达式模式或标志在一个地方而不是在每一行),试图拉取替换正则表达式条件并将标志替换为单独的变量:

To make it more readable and more manageable (i.e. easier to change the regex pattern or flags by changing it in one place instead of on every line), trying to pull the replace regex condition and replace flags out into a separate variable:

var pattern = /\b(?!\-)(?!\/)\b(?!\-)/gi;

var NewHTML = OriginalHTML
.replace("JavaScript", "<a href=\"http://js.com/\">$&</a>", pattern)
.replace("MySQL", "<a href=\"http://www.mysql.com/\">$&</a>", pattern)    

问题是,内联调用被完全忽略...正则表达式部分和标志部分。

Problem is, the inline call is being completely ignored... both the regex portion and the flags portion.

任何人都可以发现JS替换调用或regex / flags变量声明有什么问题吗? : - )

Can anyone spot what's wrong with the JS replace call or declaration of the regex/flags variable? :-)

谢谢!

推荐答案

我会使用查找将原件映射到URL的对象:

I would use a lookup object to map the originals to URLs:

// Original string
var o = "MySql is a DBMS, whereas javascript is a client side scripting language";

//Patterns
var patterns = {
    "javascript": "http://js.com/",
    "mysql": "http://www.mysql.com/"
};

//Constructing regex
RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
var keys = [];
for (i in patterns) {
    if (patterns.hasOwnProperty(i)) {
        keys.push(RegExp.escape(i));
    }
}
var pattern = new RegExp("\\b(" + keys.join("|") + ")\\b", "gi");

//Replace
var n = o.replace(pattern, function(m, g1) {
    return "<a href='" + patterns[g1.toLowerCase()] + "'>" + g1 + "< /a>";
});
console.log(n);

以下是演示: http://jsfiddle.net/qP9Er/

编辑:

根据您的要求,这里有一个替换前n次出现的版本。您可以在这里找到演示:

As per your request, here is a version that replaces the first n occurrences. You can find a demonstration here:

// Original string
var o = '<p>Test 1 (JavaScript - <strong>1st keyword instance to be replaced</strong>): <br><a href="http://js1.net">Link to JavaScript site (existing URL)</a> is a scripting language commonly implemented as part of a web browser in order to create enhanced user interfaces and dynamic websites. JavaScript is very flexible.</p><p>more text here... and another mention of JavaScript. also javascript and JAVAScrIPT <br><br></p><p>Test 2 (MySQL - <strong>1st keyword instance to be replaced</strong>): <br><a href="http://www.mysql.com">MySQL</a>  (existing URL) is the most popular open-source database system.</p> <p><a href="http://www.themysqllink.com">link to a MySQL site</a> (existing URL).</p><p> More stuff about Mysql, also mysql and mySQL</p>';

//Patterns
var patterns = {
    "javascript": "http://js.com/",
    "mysql": "http://www.mysql.com/",
    "mention": "http://www.x.com/"
};

//Number of replacements
var num = 1;

//Constructing regex
RegExp.escape = function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
var keys = [];
for (key in patterns) {
    if (patterns.hasOwnProperty(key)) {
        keys.push(RegExp.escape(key));
    }
}
var regexen = [];
for (var i = 0; i < keys.length; i++) {
    regexen[i] = new RegExp("\\b(" + keys[i] + ")\\b(?![^<]*?<\/a>)", "i");
}

//Replace
for (var i = 0; i < regexen.length; i++) {
    var count = 0;
    var pattern = regexen[i];
    while (count < num) {
        o = o.replace(pattern, function(m, g1) {
            return "<a href='" + patterns[g1.toLowerCase()] + "'>" + g1 + "</a>";
        });
        count++;
    }
}
document.write(o);

这篇关于javascript正则表达式替换,如何提供正则表达式条件(和标志)作为变量而不是内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆