Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created October 24, 2019 01:22
Show Gist options
  • Save akirattii/b80842d1ca5803e8b745a72eff0fe083 to your computer and use it in GitHub Desktop.
Save akirattii/b80842d1ca5803e8b745a72eff0fe083 to your computer and use it in GitHub Desktop.
Example: How to insert html tags efficiently.
/*
* Below example converts from "1hoge2foo3bar456" to "1<b>hoge</b>2<b>foo</b>3<b>bar</b>456".
*/
const tag = "b"; // <b> tag.
// sample message
let msg = "1hoge2foo3bar456";
/* insert point indice */
const insPoints = [
[1, 4], // "hoge"
[6, 8], // "foo"
[10, 12], // "bar"
];
let insPointsIdx = 0;
const buf = [];
msg.split("").forEach((s, idx) => {
// console.log(s, idx);
const insPoint = insPoints[insPointsIdx];
if(!insPoint) return buf.push(s);
if (idx === insPoint[0]) {
buf.push(`<${tag}>`);
}
buf.push(s);
if (idx === insPoint[1]) {
buf.push(`</${tag}>`);
insPointsIdx += 1;
}
});
console.log("buf:", buf.join("")); // buf: 1<b>hoge</b>2<b>foo</b>3<b>bar</b>456
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment