Skip to content

Instantly share code, notes, and snippets.

@rseon
Last active September 7, 2020 15:13
Show Gist options
  • Save rseon/61c034da76c4e5fdc5dc1686b8b19e6c to your computer and use it in GitHub Desktop.
Save rseon/61c034da76c4e5fdc5dc1686b8b19e6c to your computer and use it in GitHub Desktop.
Highlights a string in another
/**
* Highlights a string in another.
*
* This methods wrap the portion of ${search} found in ${str} with a ${tag} with class ${className}.
* If ${search} was not found, ${str} is returned
*
* @example highlightString('Hello World !', 'world') // "Hello <span class="highlight">World</span> !"
* @example highlightString('Hello World !', 'foo') // "Hello World !"
* @example highlightString('Hello World !', 'world', 'test', 'div') // "Hello <div class="test">World</div> !"
*
* @param {String} str
* @param {String} search
* @param {String} className
* @param {String} tag
* @returns {String}
*/
export function highlightString (str, search, className = 'highlight', tag = 'span') {
if (search && new RegExp(search, 'i').test(str)) {
const strSplit = str.split('')
const correctCase = search.split('').map((v, i) => {
return strSplit[i] === strSplit[i].toLowerCase() ? v.toLowerCase() : v.toUpperCase()
}).join('')
return str.replace(new RegExp(search, 'ig'), `<${tag} class="${className}">${correctCase}</${tag}>`)
.replace(new RegExp(`</${tag}><${tag} class="${className}">`, 'ig'), '')
}
return str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment