简体   繁体   中英

Matching multiple keywords in a text (Javascript)

Here is my code:

// Matching multiple keywords in a text
// Case 1
var text = "Hello, My name is @Steve, I love @Bill, happy new year!";
var keywords = ["steve"];
var matching = text.toLowerCase().search([keywords]);
console.log(matching);
// return 19

// Case 2
var text = "Hello, My name is @Steve, I love @Bill, happy new year!";
var keywords = ["bill"];
var matching = text.toLowerCase().search([keywords]);
console.log(matching);
// return 34

// Case 3
var text = "Hello, My name is @Steve, I love @Bill, happy new year!";
var keywords = ["steve, bill"];
var matching = text.toLowerCase().search([keywords]);
console.log(matching);
// return -1

// Case 4
var text = "Hello, My name is @Steve, I love @Bill, happy new year!";
var keywords = ["steve", "bill"];
var matching = text.toLowerCase().search([keywords]);
console.log(matching);
// return -1

If there something I missed out to make Case 3 and Case 4 return positive?

I just want if the text is either matching with one of the keywords , it will return positive .

But not working at this moment. Helps needed. Thanks.

Thanks.

Reading the docs reveals that the provided argument to the search method is converted into a regex, resulting in /steve,bill/ which searches exactly for "steve,bill" .

You'll need to provide a proper regular expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM