Reputation: 67
I have a piece of text, where I want to highlight several words. The words that need to be highlighted are defined by an array of indexes: [[10, 15], [20, 27], ...]
, these represent the start and end index of the characters that need to be highlighted.
Originally I put this together:
var content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum tincidunt consequat quam, ut convallis massa euismod at. Proin vel fermentum leo. Suspendisse erat turpis, gravida quis dui sed, mattis consectetur dolor. Curabitur nec tincidunt augue. Donec sapien eros, molestie vel volutpat vitae, vulputate sed ante. Donec finibus consequat dignissim. Donec at nibh eget nibh ultrices gravida. Fusce id molestie eros. Aenean maximus ante et mi elementum, eget pharetra mauris mollis. ";
[[10, 15], [20, 27], [39, 45]].forEach(function(pos) {
content = content.substring(0, pos[0]) + '<mark>' + content.substring(pos[0], pos[1]) + '</mark>' + content.substring(pos[1]);
})
document.querySelector("#test").innerHTML = content;
<div id="test"></div>
But this obviously doesn't work very well, since inserting the <mark>
, changes the indexes in the original text.
How would I go about making this work correctly?
Upvotes: 1
Views: 97
Reputation: 4217
you can use String#replace
, 13
is the number of characters in <mark></mark>
we use it in combination withe the index i
to translate the old indexes to updated one after each insert.
var content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum tincidunt consequat quam, ut convallis massa euismod at. Proin vel fermentum leo. Suspendisse erat turpis, gravida quis dui sed, mattis consectetur dolor. Curabitur nec tincidunt augue. Donec sapien eros, molestie vel volutpat vitae, vulputate sed ante. Donec finibus consequat dignissim. Donec at nibh eget nibh ultrices gravida. Fusce id molestie eros. Aenean maximus ante et mi elementum, eget pharetra mauris mollis. ";
[[10, 15], [20, 27], [39, 45]].forEach(function(pos,i) {
content = content.replace(content.substring(pos[0]+13*i, pos[1]+13*i),'<mark>' + content.substring(pos[0]+13*i, pos[1]+13*i) + '</mark>')
})
document.querySelector("#test").innerHTML = content;
<div id="test"></div>
Upvotes: 0
Reputation: 2566
The simplest way to do it, assuming the mark indices are sorted, would be to just reverse the array, so the remaining indices remain the same in the resulting string
[
[10, 15],
[20, 27],
[39, 45],
]
.reverse()
.forEach(function (pos) {
content =
content.substring(0, pos[0]) +
'<mark>' +
content.substring(pos[0], pos[1]) +
'</mark>' +
content.substring(pos[1]);
});
If its not sorted, replace the reverse()
with a custom sort
[
[10, 15],
[20, 27],
[39, 45],
]
.sort(function (a, b) {
return b[0] - a[0];
})
.forEach(function (pos) {
content =
content.substring(0, pos[0]) +
'<mark>' +
content.substring(pos[0], pos[1]) +
'</mark>' +
content.substring(pos[1]);
});
Upvotes: 1