Sara Ree
Sara Ree

Reputation: 3543

Match a whole sentence only if it's at the end of a string

Let's say we want to check if speech contains a specific sentence (reference) but at the last and end of it:

Here is the reference:

let reference = "have you ever look at someone";

Based on this reference we want to compare speech and return match or No match:

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'

The problem is I can't differentiate between above speech examples and the code always returns 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!")
}

Upvotes: 0

Views: 34

Answers (2)

Channa
Channa

Reputation: 3767

you can use endsWith to validate as follows,

var str = "Hello world, welcome to the universe.";
var n = str.endsWith("universe.");

in your case

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

Upvotes: 1

User2585
User2585

Reputation: 372

Is this what you're looking for?

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

Upvotes: 2

Related Questions