JavaScript - 如何为给定String中的某些单词添加粗体/强效果

时间:2015-06-02 14:49:36

标签: javascript

我试图突出显示string中的某些关键字(这些关键字作为数组中的字符串传递)。到目前为止,我能够找到这些单词的起始位置,但我无法使用<b></b>标记将它们包围起来。有任何想法吗? JSfiddle示例here

JS:

function getIndicesOf(searchStr, str) {
    var startIndex = 0;
    var index, tmp = [];

    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        tmp.push(index);
        startIndex = index + searchStr.length;
    }
    console.log(tmp);
}

var vow = "Night gathers, and now my watch begins..";
var bold=["night","watcher"];
for(var i=0;i<bold.length;i++){
    getIndicesOf(bold[i], vow);
}

document.getElementById("vow_p").innerHTML = vow;

2 个答案:

答案 0 :(得分:8)

您可以使用正则表达式捕获组执行所需操作:

如果您想要包含以下字词:Night's并且只加粗Night部分,则可以使用字边界:(\b)

如果您只想包含整个字词:请使用(^|\s)($|\s)

这样可以保持你所用词语的大写字母。

var vow = "Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come.";

var wordsToBold=["night","watcher"];

function makeBold(input, wordsToBold) {
    return input.replace(new RegExp('(\\b)(' + wordsToBold.join('|') + ')(\\b)','ig'), '$1<b>$2</b>$3');
}

document.getElementById("vow_p").innerHTML = makeBold(vow, wordsToBold);
<div id="vow_p"></div>

答案 1 :(得分:4)

我会使用正则表达式搜索单词并用<b><strong>标记将其包围。

var s = "Night gathers, and now my watch begins";
s.replace(/(night|watch)/ig, '<b>$1</b>');
// "<b>Night</b> gathers, and now my <b>watch</b> begins"

您还可以使用RegExp对象并编译数组中的单词列表:

var w = ['night', 'watch'];
var r = new RegExp('(' + w.join('|') + ')', 'ig');

var s = "Night gathers, and now my watch begins";
s.replace(r, '<b>$1</b>');
// "<b>Night</b> gathers, and now my <b>watch</b> begins"