在字符串中突出显示多个子字符串--javascript / jquery

时间:2014-12-01 22:59:41

标签: javascript jquery html ruby-on-rails

tldr:如何在javascript字符串变量中突出显示多个子字符串(可能使用黑色文本可读的不同颜色)?模拟所需输出:

sample_highlight

长版

我有一些文字:

<span>This is some text, there are lots of things in here. </span>

我还有一个包含子串的哈希值,以突出显示:

h = {"t0": [0,2], "t1" : [8,15]}

我想强调给定子串开始和结束数组的散列的文本。它看起来像这样:

Thi s 某些tex t,这里有很多东西。

我考虑过使用html标签,但我无法弄清楚如何同时替换所有子字符串:

累积尝试

第一次迭代

<tag1>Thi</tag1>s is some text, there are lots of things in here.

第二次迭代

<tag1>Th<tag2>i</tag1</tag2>>s is some text, there are lots of things in here.
        ^ this is where the new 8th index is

顺序尝试

如果我使用原始值,我不知道如何将结果添加到一起:

第一次迭代

<tag1>Thi</tag1>s is some text, there are lots of things in here.

第二次迭代

This is <tag2>some tex</tag2>t, there are lots of things in here.

大!但是如何将它们加在一起?

编辑:

标签可以很好地嵌套:

<tag1>hello <tag2>world</tag2></tag1>

不是我的正常使用案例,但我想它可能会发生。即使它只是用工具提示突出显示,这会有所帮助,我猜?

1 个答案:

答案 0 :(得分:1)

查看我放在一起的这个功能。看到它在这个JSFiddle

中工作

HTML

<span class="texttohighlight">This is some text, there are lots of things in here.</span>

JQuery的/使用Javascript

var hash = {"t0": [0,2], "tabtest" : [4,8], "t1" : [9,25]};

highlightWords(hash);

function highlightWords(hash) {
    var offset = 0;
    var original;

    $.each(hash, function(key, val) {
        original = $(".texttohighlight").html();
        var length = original.length;
        var before = original.substring(0,val[0]+offset);
        var replace = original.substring(val[0]+offset, val[1]+offset);
        var after = original.substring(val[1]+offset,length);
        var final = before + "<span class='"+key+"'>" + replace + "</span>" + after;
        offset += 22 + key.length;
        $(".texttohighlight").html(final);
    });
}

CSS

.t0 {
   background:#00ff00;
}

.t1 {
    background:#00ffff;
}

.tabtest {
    background:#ccc;
}

它使用JQuery并根据哈希中的数字创建span元素。跨度得到了关键所在的类。

“t0”:[0,2]将创建

<span id="t0">Th</span>

一些注释:

  • 不能重叠。重叠时html标签不起作用,颜色无论如何都不起作用

  • 嵌套标签不起作用,您可以添加一些条件逻辑并根据是否在之前或之后添加附加代码来更新哈希表但是您确实提到它不是您的正常用例以具有嵌套元素所以我只是为了简单而将它添加到循环中

  • 您必须按照它们出现的顺序列出子字符串。

示例:

  • {“t0”:[0,2],“tabtest”:[4,8],“t1”:[9,25]};作品

  • {“tabtest”:[4,8],“t0”:[0,2],“t1”:[9,25]};不会起作用

这是因为我们在子字符串数字上添加一个偏移量以补偿其他字符。

相关问题