简体   繁体   English

检查每个单词的主字符串中是否存在子字符串

[英]check if substring exists in main string per word

I have a string I want to check if a substring is in the main string.我有一个字符串,我想检查子字符串是否在主字符串中。 The code I have below works partially.我下面的代码部分工作。 The problem is I want to check if the substring matches per word to the main string currently it checks per character.问题是我想检查每个单词的子字符串是否与当前检查每个字符的主字符串匹配。 To Explain this better say my main string is the banana is yellow and if the substring I am looking for is banana is I want it to print true but if the substring is ana is it prints false.为了更好地解释这一点,说我的主字符串是the banana is yellow的,如果我要查找的子字符串是banana is我希望它打印为 true,但如果子字符串是ana is它打印的是 false。 How can I achieve this?我怎样才能做到这一点?

 const testString = 'the banana is yellow' const checkString = 'ana is' //should have printed false if (testString.includes(checkString)) { console.log('true') } else { console.log('false') }

Turn the needle into a regular expression surrounded by word boundaries.将指针变成被单词边界包围的正则表达式。

 const testString = 'the banana is yellow' const checkString = 'ana is' const pattern = new RegExp('\\b' + checkString + '\\b'); console.log(pattern.test(testString));

If the needle might contain special characters, escape them before passing to the RegExp constructor.如果 needle 可能包含特殊字符,请在传递给 RegExp 构造函数之前对其进行转义

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

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