Skip to content

Instantly share code, notes, and snippets.

@wicksome
Created January 17, 2019 14:27
Show Gist options
  • Save wicksome/cc88693ec5ef71491c30153d3a41c793 to your computer and use it in GitHub Desktop.
Save wicksome/cc88693ec5ef71491c30153d3a41c793 to your computer and use it in GitHub Desktop.
highlight method(case insensitive, escape, etc...)
export const escapeHtml = string => string.replace(/[&<>"'/`=]/g, s => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
"\"": "&quot;",
"'": "&#39;",
"/": "&#x2F;",
"`": "&#x60;",
"=": "&#x3D;",
})[s]);
export const unescapeHtml = string => string.replace(/&([a-z]+|#[0-9]+);/g, s => ({
"amp": "&",
"lt": "<",
"gt": ">",
"quot": "\"",
"#39": "'",
"#x2F": "/",
"#x60": "`",
"#x3D": "=",
})[s]);
/**
* highlight.
* @param text origin text
* @param keyword target keyword
* @param element html element
* @param clazz class array
* @param escape is escape
* @param caseInsensitive case
* @returns {string}
*/
export const highlight = ({text = "", keyword = "", element = "strong", clazz = [], escape = false, caseInsensitive = false}) => {
if (!text) return text;
if (!keyword) return escape ? escapeHtml(text) : text;
const regex = new RegExp(keyword, caseInsensitive ? "ig" : "g");
const indices = [];
let matched;
while ((matched = regex.exec(text))) {
indices.push(matched.index);
}
let idx = 0;
let result = "";
for (const startIndex of indices) {
const other = text.substring(idx, startIndex);
const matchedText = text.substring(startIndex, startIndex + keyword.length);
result += `${escape ? escapeHtml(other) : other}<${element}${clazz.length === 0 ? "" : ` class="${clazz.join(" ")}"`}>${escape ? escapeHtml(matchedText) : matchedText}</${element}>`;
idx = startIndex + keyword.length;
}
result += escape ? escapeHtml(text.substring(idx, text.length)) : text.substring(idx, text.length);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment