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

前端之家收集整理的这篇文章主要介绍了javascript为部分字符串创建工具提示,该字符串尚未在工具提示下前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个像这样的字符串:
"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/

原文链接:https://www.f2er.com/js/150153.html

猜你在找的JavaScript相关文章