Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native: Check if string contains string

My goal is it to create a search ListView with JSON Data. This is working but I have a tiny problem with the search function. When I type in a word, it has to be exactly the same word, which is in the Array of the ListView. The main problem is that I have to type in the correct word. For example: when the word stackoverflow is one item of the Array, I have to type in stackoverflow to find this item. But I want to get the Item also when I type in stack or flow or stacko for example.

This is my code:

    filterDatasource(event)
  {
      var searchString = event.nativeEvent.text.toLowerCase();
      if (searchString != "")
      {

          var content = this.state.loadedContent;
          var searchResultsArray = [];

          for (var i = 0; i < content.length; i++) {


            var detailArray = content[i];
            const gattung = detailArray.Gattung;
            const zugnummer = detailArray.Zugummer;
            const ab = detailArray.ab;
            const bis = detailArray.bis;
            const wochentag = detailArray.Wochentag;
            const zeitraum = detailArray.Zeitraum;


            if (searchString.contains(ab.toLowerCase())) //searchString.indexOf(ab) >= 0
            {

                //alert('gefunden');
                searchResultsArray.push(detailArray);
                this.setState({ dataSource: ds.cloneWithRows(searchResultsArray) });

            }


          }

      }
      else {

        this.setState({ dataSource: ds.cloneWithRows(this.state.loadedContent) });

      }
  },
like image 666
profidash_98 Avatar asked Jul 27 '16 10:07

profidash_98


People also ask

How do I check if a string contains a character in react?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.

How do you check if a string contains a substring?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.


1 Answers

You can do this with indexOf like this:

if (searchString.indexOf(ab.toLowerCase()) > -1)
{ 
     ...
}
like image 114
babadaba Avatar answered Oct 13 '22 01:10

babadaba