Skip to content

Instantly share code, notes, and snippets.

@GingerBear
Last active April 27, 2017 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GingerBear/49d5f6c4bc1dae1949a982b555ce5a07 to your computer and use it in GitHub Desktop.
Save GingerBear/49d5f6c4bc1dae1949a982b555ce5a07 to your computer and use it in GitHub Desktop.
highlights string by keyword, split into pieces, keep character case
function highlightStr(name, query) {
if (!query)
return [
{
str: name,
isHighlight: false
}
];
const queryRegx = new RegExp(query, "ig");
const matches = name.match(queryRegx);
if (!matches)
return [
{
str: name,
isHighlight: false
}
];
const textSplits = name.split(queryRegx).reduce((acc, item) => {
item &&
acc.result.push({
str: item,
isHighlight: false
});
matches[acc.matchIndex] &&
acc.result.push({
str: matches[acc.matchIndex],
isHighlight: true
});
acc.matchIndex += 1;
return acc;
}, { result: [], matchIndex: 0 });
return textSplits.result;
}
test('ABCDEFABKDEAbSB', 'ab')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment