Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. function highlightStr(name, query) {
  2. if (!query)
  3. return [
  4. {
  5. str: name,
  6. isHighlight: false
  7. }
  8. ];
  9.  
  10. const queryRegx = new RegExp(query, "ig");
  11. const matches = name.match(queryRegx);
  12.  
  13. if (!matches)
  14. return [
  15. {
  16. str: name,
  17. isHighlight: false
  18. }
  19. ];
  20.  
  21. const textSplits = name.split(queryRegx).reduce((acc, item) => {
  22. item &&
  23. acc.result.push({
  24. str: item,
  25. isHighlight: false
  26. });
  27. matches[acc.matchIndex] &&
  28. acc.result.push({
  29. str: matches[acc.matchIndex],
  30. isHighlight: true
  31. });
  32. acc.matchIndex += 1;
  33. return acc;
  34. }, { result: [], matchIndex: 0 });
  35.  
  36. return textSplits.result;
  37. }
  38.  
  39. test('ABCDEFABKDEAbSB', 'ab')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement