Reputation: 2062
I'm trying to highlight certain keywords inside a string
(these keywords passed as strings in an array). So far I'm able to find where these words start, but I can't obviously surround them with <b></b>
tags. Any ideas?
JSfiddle example 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;
Upvotes: 4
Views: 17666
Reputation: 39287
You can use regex capture groups to do what you want:
If you want to include words like : Night's
and only bold the Night
part you can use word boundries: (\b)
If you want to only include entire words: use (^|\s)
and ($|\s)
This maintains the capitalization of the words you are bolding.
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>
Upvotes: 10
Reputation: 4091
I would use a regular expression to search for words and surround them with a <b>
or <strong>
tag.
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"
You can also use a RegExp
object and compile the list of words from an array:
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"
Upvotes: 5