regex 包含尊重单词的功能[重复]

fjnneemd  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(86)

此问题在此处已有答案

How can I match a whole word in JavaScript?(4个答案)
11天前关闭。
我们有这个字符串:

const baseReference = 'they can fix a spinal if you got the money';

字符串
如果我们想检查字符串是否包含单词或短语,我们可以简单地执行:

1) baseReference.includes('spinal'); // returns true

2) baseReference.includes('got the money'); // returns true


问题是includes方法不尊重单词,所以这个方法也返回true

3) baseReference.includes('spin');  // returns true but there is no word as spin in the string


我想使用includes方法来检查字符串是否包含短语,但相对于每个单词,因此我们得到以下结果:

1) baseReference.includes('spinal'); // should returns true
2) baseReference.includes('got the money'); // should returns true
3) baseReference.includes('spin'); // should returns false because we don't have spin as a word in the sring


我尝试使用split(' ')将字符串转换为单词,然后使用filter检查是否包含匹配,但使用我的方法,我不能检查像got the money这样的短语,对吗?
你会怎么做

kadbb459

kadbb4591#

你可以使用regex test方法,这样你就可以在开始和结束时指定断字,如下所示:

const baseReference = "We got the money, but not the gold!";
console.log(/\bgot the money\b/.test(baseReference)); // true
console.log(/\bnot the gol\b/.test(baseReference)); // false

字符串
如果要搜索的文本是动态的(你在变量中有它),那么像这样构造RegExp对象:

const baseReference = "We got the money, but not the gold!";
const find = "money";

const regex = RegExp(String.raw`\b${find}\b`);
console.log(regex);
console.log(regex.test(baseReference)); // true

uinbv5nw

uinbv5nw2#

@trincot 的答案的基础上,您可以进一步在String类原型中创建一个函数,该函数允许您从字符串本身执行测试,类似于String.includes()

// Create a function inside the String class prototype itself
// You may want to give it a more helpful name ;)
String.prototype.respectfulIncludes = function(word) {
    return RegExp(String.raw`\b${word}\b`).test(this);
}

const baseReference = 'they can fix a spinal if you got the money';
console.log(baseReference.respectfulIncludes('spinal'));
console.log(baseReference.respectfulIncludes('got the money'));
console.log(baseReference.respectfulIncludes('spin'));

字符串

相关问题