insert HTML
by Paco86
HTML
<!--
give intervals, for example, [0, 3, 'b'],
0 is start position (includesive),
3 is end position <excludesive>,
b is tag name
so use intervals as input, [0, 3, 'b'], [2, 4,'i'], and another string as input "abc",
the output will calulate overlaying and insert tage to string.
abcedfgh -> <b>ab</b> <b><i>c</i></b> <i>c</i>
-->
<div id="test"></div>
JavaScript
var intervals = [[0, 3, 'b'], [7, 22, 'i'], [13, 30, 'b']];
var string = 'abcedfdqwdwqdqkqofmkkoejwlwekndmwemoqcnsaihdnscmalsdkcmdsknclmacwdqwdqw';
var insertHtml = function(intervals, string) {
var newIntervals = intervals.reduce((acc, cur) => {
acc.push({
index: cur[0],
tag: `<${cur[2]}>`
});
acc.push({
index: cur[1] - 1,
tag: `</${cur[2]}>`
});
return acc;
}, []);
newIntervals.sort((a, b) => {
return b.index - a.index;
});
var arr = string.split('');
for (var i = 0; i < newIntervals.length; i++) {
arr.splice(newIntervals[i].index, 0, newIntervals[i].tag);
}
document.getElementById('test').innerHTML = arr.join('');
var res = document.getElementById('test').innerHTML;
console.log(res)
return res;
};
insertHtml(intervals, string);