Filter strings in Array based on content

前端 未结 4 1432
予麋鹿
予麋鹿 2020-11-28 14:23

I am running into an issue, I have a similar array of Strings in JS:

var myArray = [\"bedroomone\", \"bedroomonetwo\", \"bathroom\"];

And I

相关标签:
4条回答
  • 2020-11-28 15:06

    You could also use the search() method

    Finds the first substring match in a regular expression search.

    (method) String.search(regexp: string | RegExp): number (+1 overload)

    const filterList = (data, query) => {
            return data.filter(name => name.toLowerCase().search(query.toLowerCase()) !== -1);
          };
    
    0 讨论(0)
  • 2020-11-28 15:11

    String.prototype.indexOf:

    var PATTERN = 'bedroom',
        filtered = myArray.filter(function (str) { return str.indexOf(PATTERN) === -1; });
    

    Regexp:

    var PATTERN = /bedroom/,
        filtered = myArray.filter(function (str) { return PATTERN.test(str); });
    

    String.prototype.includes (only in moderm browsers):

    var PATTERN = 'bedroom',
        filtered = myArray.filter(function (str) { return str.includes(PATTERN); });
    
    0 讨论(0)
  • 2020-11-28 15:17

    Improved Microfed's answer to this

    var textToSearch = 'bedroom';
    var filteredArray = myArray.filter((str)=>{
      return str.toLowerCase().indexOf(textToSearch.toLowerCase()) >= 0; 
    });
    
    0 讨论(0)
  • 2020-11-28 15:21
    var bedrooms = myArray.filter(name => name.includes('bedroom'))
    
    0 讨论(0)
提交回复
热议问题