我有一个像这样的字符串:
"Size: 40; Color: 30"
Run Code Online (Sandbox Code Playgroud)
我想为他们创建工具提示,使其看起来像这样:
<span class='tooltip' data-tooltip='The Size of a Unit is controlled by the Color of the Unit.'>Size</span>: 40; <span class='tooltip' data-tooltip='The Color of a Unit is a standard Setting.'>Color</span>: 30
Run Code Online (Sandbox Code Playgroud)
然而,使用天真的替换,我最终得到这个:
<span class='tooltip' data-tooltip='The Size of a Unit is controlled by the <span class='tooltip' data-tooltip='The Color of a Unit is a standard Setting.'>Color</span> of the Unit.'>Size</span>: 40; <span class='tooltip' data-tooltip='The Color of a Unit is a standard Setting.'>Color</span>: 30
Run Code Online (Sandbox Code Playgroud)
这不是我想要的.如何编写正则表达式或进行替换以使其不替换已经属于工具提示的文本?
编辑:我没有说明替换不是尺寸和颜色,它们只是示例.我正在添加任意数量,通常是20多个工具提示到任何字符串.
以下是一些可测试的:
var tooltips = {
"Size":"The Size of a Unit is controlled by the Color",
"Color": "bar",
"Time and Size": "foo"
}
"Here we have something of <b>Size</b> 20 and Color red. it's very important that the Time and Size of the work and kept in sync."
Run Code Online (Sandbox Code Playgroud)
应该导致:
"Here we have something of <b><span class='tooltip' data-tooltip='The Size of a Unit is controlled by the Color'>Size<span></b> 20 and <span class='tooltip' data-tooltip='bar'>Color<span> red. it's very important that the <span class='tooltip' data-tooltip='foo'>Time and Size<span> of the work and kept in sync."
Run Code Online (Sandbox Code Playgroud)
较长的匹配应优先于较短的匹配.它应该只匹配整个单词而不是单词的一部分.
编辑:忘了陈述另一个要求.
它仍应匹配用非工具提示的标签包装的字符串.
我认为如果有正确的正则表达式模式,单个 str.replace 就可以完成工作。
function replaceTooltips(str, tooltips) {
//copy from https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var keys = [];
for ( var k in tooltips) {
keys.push(escapeRegExp(k));
}
//create a regexp like (Size)|(Color)|(Time and Size)
var ptn = new RegExp('(' + keys.join(')|(') + ')', 'g');
str = str.replace(ptn, function(mat) {
if (!tooltips[mat]) {
return mat;
}
return '<span class="tooltip" data-tooltip="' + tooltips[mat].replace(/"/g, '"') + '">' + mat + '</span>';
});
return str;
}
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/rooseve/6wRUF/