Last active
April 27, 2017 18:47
-
-
Save GingerBear/49d5f6c4bc1dae1949a982b555ce5a07 to your computer and use it in GitHub Desktop.
highlights string by keyword, split into pieces, keep character case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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