Confirm the Ending by Mohit

Why cant we do the below code with using only regular expressions.

function confirmEnding(str, target) {
  var num = str.length-target.length;
  var newString=str.slice(num);
 return newString == target;
   
}

function confirmEndingNew(str, target) {
  var targetRegex = /target$/;
  return targetRegex.test(str) ;
}

Because /target$/ looks to match the actual letters target at the end of the string instead of a variable.

To use target as a variable, you have to do something a little different. An example (but not the actual code you would use for this challenge is below).

Let’s say you wanted to test a string (a sentence) to see if it had an animal name/type in it. If you had only a few animal types you were looking for, you could do the following.

function foundAnimalInSentence(sentence) {
  const regex = /cat|dog|bird/;
  return regex.test(sentence);
}

foundAnimalInSentence('The traffic was bad today.'); // false
foundAnimalInSentence('The dog ran across the road'); // true

What if you had a large list (a million or more) animal types you wanted to check. It would not be practical to construct a regular expression with all those animal names. Instead, you would probably have an array or object contain animal types and then use a RegExp constructor to build each regular expression to test for the animal. The example below contains a small array of animal types, but you should get the idea.

function foundAnimalInSentence(animals, sentence) {
  return animals.some(animal => {
    const regex = new RegExp(animal);
    return regex.test(sentence);
  });
}

const animals = ['cat', 'dog', 'bird', 'bear', 'elephant', 'horse'];
foundAnimalInSentence(animals, 'The traffic was bad today.'); // false
foundAnimalInSentence(animals, 'The dog ran across the road'); // true
1 Like

Thanks a lot for the reply.