仅在字符串末尾匹配整个句子
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了仅在字符串末尾匹配整个句子相关的知识,希望对你有一定的参考价值。
比方说,我们要检查speech
是否包含特定句子(reference
)但在它的最后和结尾:
这里是reference
:
let reference = "have you ever look at someone";
基于此reference
,我们想比较speech
并返回匹配项或不匹配项:
let speech = "blaaaah have you ever look at someone"; // Match because 'have you ever look at someone' is at the end of speech
let speech = "have you ever look at someone blaaaah"; // No match because something else came after 'have you ever look at someone'
问题是我无法区分上述语音示例,并且代码始终返回Match:
//let speech = "blaaaah have you ever look at someone"; // matched
let speech = "have you ever look at someone blaaaah"; // No match
let reference = "have you ever look at someone";
if(new RegExp("\\b"+reference+"\\b").test(speech))
console.log("Finally Matched!")
else
console.log("No Match At Last!")
答案
这是您要寻找的吗?
//let speech = "blaaaah have you ever look at someone"; // matched
let speech = "have you ever look at someone blaaaah"; // No match
let reference = "have you ever look at someone";
if(new RegExp("\\b"+reference+"\\b$").test(speech))
console.log("Finally Matched!")
else
console.log("No Match At Last!")
另一答案
您可以使用endsWith
进行如下验证,
var str = "Hello world, welcome to the universe.";
var n = str.endsWith("universe.");
根据您的情况
//let speech = "blaaaah have you ever look at someone"; // matched
let speech = "have you ever look at someone blaaaah"; // No match
let reference = "have you ever look at someone";
if(speech.endsWith(reference))
console.log("Finally Matched!")
else
console.log("No Match At Last!")
以上是关于仅在字符串末尾匹配整个句子的主要内容,如果未能解决你的问题,请参考以下文章