admin管理员组

文章数量:1392002

I have array that contain strings

mentArray ={ "words":[ "xyz", "abc", "random", "sample" ] }

And I want to match string

 var ment = "hello world ran"

What I'm doing is

mentArray.words.find(words => {
    if (ment.toLowerCase().includes(words.toLowerCase())) {
      return true;
    }
  });

it giving true because "random" contains "ran" but I want true only if matches whole string not characters.

I have array that contain strings

mentArray ={ "words":[ "xyz", "abc", "random", "sample" ] }

And I want to match string

 var ment = "hello world ran"

What I'm doing is

mentArray.words.find(words => {
    if (ment.toLowerCase().includes(words.toLowerCase())) {
      return true;
    }
  });

it giving true because "random" contains "ran" but I want true only if matches whole string not characters.

Share Improve this question asked Mar 5, 2019 at 8:41 chetan kumarchetan kumar 132 silver badges5 bronze badges 1
  • 3 Use === instead of .includes? – CertainPerformance Commented Mar 5, 2019 at 8:42
Add a ment  | 

5 Answers 5

Reset to default 3

You can do this:

const mentArray = {
    "words": [ "xyz", "abc", "random", "sample" ] 
};

const ment = "hello world ran";
const mentArr = ment.split(' ');

mentArray.words.find(words => {
    if (mentArr.includes(words.toLowerCase())) {
        return true;
    }
});

var mentArray ={ "words":[ "xyz", "abc", "random", "sample" ] }

 var ment = "hello world random";
 var mentInWords = ment.split(" ");
 var res = mentArray.words.filter(words => {
    let a = _.includes(mentInWords,words.toLowerCase())
        if (a) {
          return true;
        }else{
          return false;
      }
 });

 console.log(res)
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

var mentArray ={ "words":[ "xyz", "abc", "random", "sample" ] };
var ment = "hello xyz";
var mentInWords = ment.split(" ");
 var res = mentArray.words.filter(words => {
   for(var i = 0; i <= mentInWords.length; i++){
    var a = (mentInWords[i] == words.toLowerCase());
        if (a) {
          return true;
        }
   }
 });

 console.log(res)

1) Split the string "ment" into array of words

2) For each word from ment, try to find it in you "words" array. You can use something like your parison but you need to pare with === instead of includes, of course.

mentArray.words.some( word => ~ment.split(" ").indexOf(word))

本文标签: javascriptHow to match string to array of stringStack Overflow