Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript为';它还没有在工具提示下_Javascript_Regex - Fatal编程技术网

javascript为';它还没有在工具提示下

javascript为';它还没有在工具提示下,javascript,regex,Javascript,Regex,我有这样一个字符串: "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.'>Colo

我有这样一个字符串:

"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
我想为它们创建工具提示,使其看起来像这样:

"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
尺寸:40;颜色: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
尺寸:40;颜色: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."
var工具提示={
“大小”:“单位大小由颜色控制”,
“颜色”:“条”,
“时间和大小”:“foo”
}
“这里我们有20号的红色。工作的时间和大小保持同步非常重要。”
应导致:

"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."
“这里我们有20号的红色。工作的时间和大小保持同步非常重要。”
较长的匹配应优先于较短的匹配。它应该只匹配整个单词,而不是部分单词

编辑:忘记陈述另一个需求


它仍然应该匹配使用非工具提示的标记包装的字符串。

如果它们总是由
分隔然后您应该在那里拆分字符串,用适当的字符串替换每个部分,然后再次连接它们

差不多

var tooltips = {
        'size': 'The Size of a Unit is controlled by the Color of the Unit.',
        'color': 'The Color of a Unit is a standard Setting.'
        ..etc..
    },
    myString = "Size: 40; Color: 30",
    stringParts = myString.split(';');

for (var i = 0, len = stringParts.length; i < len; i++){
   var pair = stringParts[i].split(':'),
       key = pair[0].trim().toLowerCase(),
       tip = tooltips[key];

  if (tip){
     pair[0] = '<span class="tooltip" data-tooltip="'+ tip +'">' + key + '</span>';
  }
  }

  stringParts[i] = pair.join(':');
}

alert( stringParts.join('; ') );
var工具提示={
“大小”:“单位的大小由单位的颜色控制。”,
“颜色”:单位的颜色是标准设置
等
},
myString=“大小:40;颜色:30”,
stringParts=myString.split(“;”);
对于(变量i=0,len=stringParts.length;i

如果您的浏览器本机不支持
.trim()
功能,请在

找到一个实现,我将使用以下方法:

//usual regex
var re = new RegExp("("+key+")(?!(?:<|.+?'>))", "g");

//regex to be applied on reversed string, same concept as regex above
var reRev = new RegExp("("+key.reverse()+")(?!(?:.+'=|>))", "g");

//start of the span tag including the tooltip
var repl = "<span class='tooltip' data-tooltip='"+value+"'>";
//end of the span tag
var replEnd = "</span>";

//first replacement
output = output.replace(re, repl+"$1"+replEnd);

//now reverse the whole string and do a second replacement,
//this, together with the reversed regex (which uses a lookahead) mimics a lookbehind (which is unfortunately not available in JS)
output = output.reverse().replace(reRev, replEnd.reverse()+"$1"+repl.reverse()).reverse();

只需循环浏览字符串中的单词,如果找到单词的工具提示,请将其替换为工具提示范围:

var s1 = '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.',

    // replace object
    rep = {
        size: '<span class="tooltip" data-tooltip="The Size of a Unit is controlled by the Color of the Unit.">Size</span>',
        color: '<span class="tooltip" data-tooltip="The Color of a Unit is a standard Setting.">Color</span>',
        'time and size': '<span class="tooltip" data-tooltip="Time and Size tooltip">Foo</span>'
    },

    // build RegExp out of replace object keys
    reg = new RegExp('(' + Object.keys(rep).join(')|(') + ')', 'ig');

    // replace
    s2 = s1.replace(reg, function(s) {
        return rep[s.toLowerCase()] ? rep[s.toLowerCase()] : s;
    });


console.log(s2);
var s1='这里我们有20号的东西,红色的。工作的时间和规模保持同步非常重要。”,
//替换对象
代表={
大小:'大小',
颜色:“颜色”,
“时间和大小”:“Foo”
},
//使用替换对象键生成RegExp
reg=newregexp('('+Object.keys(rep.join(')|(')+'),'ig');
//替换
s2=s1。替换(reg,功能){
返回rep[s.toLowerCase()]?rep[s.toLowerCase()]:s;
});
控制台日志(s2);

如果没有多个单词的替换,就可以这么简单

var tooltips = {
  "Size":"The Size of a Unit is controlled by the Color",
  "Color": "bar",
  "Time and Size": "foo"
}

var text = "Here we have something of Size 20 and Color red. it's very important that the Time and Size of the work and kept in sync."

var replaced = text.split(" ").map(function(token) {
    return tooltips[token] || token;
}).join(" ");

我认为如果得到正确的regexp模式,一个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;

}
函数替换工具提示(str,工具提示){
//抄袭https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
函数escapeRegExp(字符串){
返回字符串.replace(/([.*+?^=!:${}()\[\]\/\]])/g,“\\$1”);
}
var键=[];
用于(工具提示中的变量k){
按键。按(escapeRegExp(k));
}
//创建类似(大小)|(颜色)|(时间和大小)的regexp
var ptn=newregexp('('+keys.join(')|(')+'),'g');
str=str.replace(ptn,功能(mat){
如果(!工具提示[mat]){
返回垫;
}

return“许多其他答案只是核心问题的创可贴:有时搜索可以在其他字符串的替换中找到。

例如,其他一些简单的解决方案很容易崩溃:

  • 更改顺序(如果两者都包含另一个则不起作用)
  • 向前看或向后看(如果替换模板发生更改,加上众所周知的HTML正则表达式解析困难,则不起作用)
但如果我们回顾一下核心问题,有一个显而易见的解决方案:

不要让替代品被替换。

因此,改为进行两次传递。步骤:

  • 不要使用对象/字典而是使用对象数组。每个项目都应该是
    {search:“Size”,tooltip:“Long description”}
  • 根据搜索字符串的长度对数组进行排序(您说过希望优先顺序更长,所以就是这样)
  • 遍历数组并按顺序替换所有关键字,其中包含数组中索引的唯一字符串。例如大小和颜色变为###替换0###
  • 再次迭代并用工具提示替换所有唯一字符串,使########变为
    大小和颜色

  • 这样,整个操作就像一个搜索/替换,不可能替换其他替换中的匹配项。

    可以使用jQuery查找元素中的所有文本节点。之后,可以使用DOM函数(而不是regex)要拆分指定单词周围的文本,请将该单词包装在工具提示中。以下是一个示例:

    var tooltips = {
      "Size":"The Size of a Unit is controlled by the Color",
      "Color": "bar",
      "Time and Size": "foo"
    }
    
    var text = "Here we have something of Size 20 and Color red. it's very important that the Time and Size of the work and kept in sync."
    
    var replaced = text.split(" ").map(function(token) {
        return tooltips[token] || token;
    }).join(" ");
    
    function replaceTextWithSpan(node, text, options) {
        var searchText = text.toLowerCase(),
            currentNode = node,
            matchIndex,
            newTextNode,
            newSpanNode;
        while ((matchIndex = currentNode.data.toLowerCase().indexOf(searchText)) >= 0) {
            newTextNode = currentNode.splitText(matchIndex);
            currentNode = newTextNode.splitText(searchText.length);
            newSpanNode = document.createElement("span");
            newSpanNode.className = "tooltip";
            newSpanNode.setAttribute("data-tooltip", options["data-tooltip"]);
            currentNode.parentNode.insertBefore(newSpanNode, currentNode);
            newSpanNode.appendChild(newTextNode);
        }
    }
    
    还有一个测试:

    <div id="test">Size: 40; Color: 30; <b>Bold Size Test:</b> 20; <span>Another Size Test: 10</span></div>
    
    结果:

    <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;
    <b>Bold <span class="tooltip" data-tooltip="The Size of a Unit is controlled by the Color of the Unit.">Size</span> Test:</b> 20;
    <span>Another <span class="tooltip" data-tooltip="The Size of a Unit is controlled by the Color of the Unit.">Size</span> Test: 10</span>
    
    下面是一个测试:

    var node = document.createElement("div");
    node.innerHTML = "Size: 40; Color: 30; Span: For testing";
    replaceTextWithSpan(node, "Size", { className: "highlight" });
    replaceTextWithSpan(node, "Color", { className: "highlight" });
    replaceTextWithSpan(node, "Span", { className: "highlight" });
    alert(node.innerHTML);
    
    这将产生以下输出(打印精美):

    尺寸:40;
    颜色:30;
    Span:用于测试
    

    您可以使用以下代码:

    var tooltips = {
      "Size":"The Size of a Unit is controlled by the Color",
      "Color": "bar",
      "Time and Size": "foo"
    }
    
    var str="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."
    
    
        var len=0;
        var res=str;
        var rep="<span class='tooltip' data-tooltip='";
           $.each(tooltips, function(key, value) { 
               var patt1=new RegExp(key);
               var ar=patt1.exec(str);
    
               var repstr=rep+value+"'>"+key+"<span>";
                   res=res.substr(0,ar.index+len)+repstr+res.substr(ar[0].length+ar.index+len);
               len+=repstr.length-key.length;
    
    
            });
        alert("result:" +res);
    
    var工具提示={
    “大小”:“单位大小由颜色控制”,
    “颜色”:“条”,
    “时间和大小”:“foo”
    }
    var str=“这里我们有20号的红色。工作的时间和大小保持同步非常重要。”
    var-len=0;
    var-res=str;
    var rep=“”+键+”;
    res=res.substr(0,ar.index+len)+repstr+res.substr(ar[0]。length+ar.index+len);
    len+=repstr.length-key