Частичный поиск строки и выделение - React Native - PullRequest
0 голосов
/ 04 мая 2020

Ниже мой код, который я использовал, чтобы выделить значения поиска в моем списке. Я использовал функцию «getHighlightedText» и передал эту функцию в свой список.

getHighlightedText = text => {
      const {value} = this.props;   //search value stored in this.state.value
      const space = new RegExp('\\b\\B\\W+\\B\\b]', 'g');
      const findWords = value.split(space).map(fw => fw.toLowerCase());  //value is split
      console.log('split the value:', findWords)
      const textWords = text.split(space);    //text is split
      console.log('split the search:', textWords)


      const output = textWords.map( word => {     //each word in the array is mapped
          const lower = word.toLowerCase();
            if(findWords.includes(lower)){        //logic to check search value includes word
            return <Text style={{ backgroundColor: 'coral'}}>{word} </Text> 
          } else {
            return <Text>{word} </Text> 
          }
      });
      return <Text>{output}</Text> 
    }



return 
<Text> {getHighlightedText(Desc)} </Text>;  //using my getHighlightedText in my renderItem

Этот лог c отлично работает только для полных строк, а не для частичных строк. На изображении ниже «json» и «url» выделены правильно. Но так как я набрал «Noti», а не «Notification», эта строка не выделяется.

enter image description here

Как мне этого добиться ?? Любые идеи, пожалуйста,

1 Ответ

0 голосов
/ 06 мая 2020

изменил мою функцию выделения, и она работает.

<Text numberOfLines={3} style={[subTitle,{fontSize:normalizeFontSize(14),lineHeight:normalizeLineHeight(14)}]}>

{getHighlightedText(alert)}

</Text>

функция выделения:

getHighlightedText = text => {
      const {value} = this.props;      //search text user inputs

      if(value == "" || value == null || value == 0){
        return <Text> {text} </Text>
      }
      else{
      const words = value.split(/\s+/g).filter(word => word.length);   //split the search value
      const pattern = words.join('|');              //join if search value has more than 1 word

      const re = new RegExp(pattern, 'gi')       
      const children = [];

      let before, highlighted, match, pos = 0;
      const matches = text.match(re);        //match using RegExp with my text


      if(matches != null){
      for( match of matches ){            // loop all the matches
        match = re.exec(text)

        if(pos < match.index) {
          before = text.substring(pos, match.index);    // before has all the text before the word that has to highlighted

          if(before.length){
            children.push(before)
          }
        }

        highlighted = <Text style={{ backgroundColor: 'coral'}}>{match[0]} </Text> 
        children.push(highlighted);       // text is highlighted

        pos = match.index + match[0].length;
      }
    }

      if(pos < text.length){
        const last = text.substring(pos);      // text after the highlighted part
        children.push(last);
      }
      return <Text>{children} </Text>          //children array will have the entire text
    }

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...