0

I need to change a background of a character in the span depending on inputted value. But! I have to check an entry depending on specific order of inputted value. For example, if i have inputted "Inv", i want to change a background only for 3 letters in "Inventory" element, not all "i", "n", "v" entries in the sidebar

This is what I have for now.

  backgroundColorSetter(item) {
    const spans = item.name.split("").map((char) => (this.inputCharsArray && this.inputCharsArray.includes(char)
        ? this._spanBackgroundSetter(char)
        : this._spanNoBackgroundSetter(char)));
    return spans;
  }
Ian
  • 77
  • 1
  • 9

1 Answers1

0

Get the index of each match. Then, characters at index i should be highlighted if for any match index m, i >= m and i < m + l (where l is the length of your match):

const matchStr = 'Inv';
const str = listItems.name;

// https://stackoverflow.com/questions/2295657/return-positions-of-a-regex-match-in-javascript
const re = new RegExp(matchStr, 'gi'); // Remove i to be case sensitive
const matchIndices = [];
let match;
while ((match = re.exec(str)) !== null) {
    matchIndices.push(match.index);
}

const spans = listItem.name.split("").map((char, charIndex) => {
    const highlight = matchIndices.some(mIndex => charIndex >= mIndex && charIndex < mIndex + matchStr);
    // return ...
});

To make it more efficient, group the characters ahead of time based off whether or not they're in a match. Then, you only need a span for each change in background rather than for every character.

DemiPixel
  • 1,768
  • 11
  • 19
  • thanks, sir! how can i use it with ternary as i did in my example? – Ian Apr 06 '21 at 23:14
  • If you're just talking about inside the map, you can do `return highlight ? ... : ...`. Another option is completely remove highlight variable and just do `(char, charIndex) => matchIndices.some(...) ? ... : ...` – DemiPixel Apr 06 '21 at 23:24
  • For some reason, getting "Aw,Snap" problem while using it. – Ian Apr 06 '21 at 23:41
  • "Aww snap" is a chrome crash, right? Only thing I could imagine is if there was an infinite loop or something--what do you have to comment out so that it starts working again? – DemiPixel Apr 06 '21 at 23:43
  • hmmm...maybe the problem with while loop – Ian Apr 06 '21 at 23:49
  • If commenting out the while loop does fix it, I suppose you could print out what "match" is each loop. Be careful not to remove the "g" from the RegExp or else it will result in an infinite loop. – DemiPixel Apr 06 '21 at 23:50
  • Unfortunately, that doesn't help at all – Ian Apr 06 '21 at 23:54