仅当它位于字符串的末尾时才匹配整个句子

假设我们要检查是否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'

问题是我无法区分上述语音示例并且代码总是返回匹配:


//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!")

}


MMTTMM
浏览 179回答 2
2回答

守着一只汪

这是你要找的吗?//let speech = "blaaaah have you ever look at someone"; // matchedlet 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"; // matchedlet 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!")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript