gpt4 book ai didi

javascript为尚未在工具提示下的部分字符串创建工具提示

转载 作者:数据小太阳 更新时间:2023-10-29 05:10:22 24 4
gpt4 key购买 nike

我有这样一个字符串:

"Size: 40; Color: 30"

我想为他们创建工具提示,如下所示:

 <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

使用天真的替代品但是我最终得到了这个:

 <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

这不是我想要的。如何编写正则表达式或以不替换工具提示中已有文本的方式进行替换?

编辑:我没有说清楚替换不是尺寸和颜色,它们只是示例。我正在向任何字符串添加任意数量的工具提示,通常是 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."

应该导致:

"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."

较长的匹配应优先于较短的匹配。它应该只匹配整个单词而不是单词的一部分。

编辑:忘了说明另一个要求。

它仍应匹配用不是工具提示的标签包裹的字符串。

最佳答案

我认为如果有正确的正则表达式模式,单个 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, '&quot;') + '">' + mat + '</span>';
});

return str;

}

http://jsfiddle.net/rooseve/6wRUF/

关于javascript为尚未在工具提示下的部分字符串创建工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21060932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com