简体   繁体   English

匹配文本中的多个关键字(JavaScript)

[英]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? 如果我错过了一些使案例3和案例4返回正值的东西?

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" . 阅读文档后发现,为search方法提供的参数已转换为正则表达式,从而导致/steve,bill/精确搜索"steve,bill"

You'll need to provide a proper regular expression. 您需要提供正确的正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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