ルックアップオブジェクトを使用して、オリジナルをURLにマップします。
// 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回の出現を置き換えるバージョンです。ここでデモンストレーションを見つけることができます:
// 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);