Check if String ends with Substring in JavaScript-Code Examples

Radu TM

Check if String ends with Substring in JavaScript

JavaScript by Radu TM โ€ข June 22, 2022

const checkEnding = (str, sub) => {
  // if the length of the substring is greater than the string, return false
  if (sub.length > str.length) {
    return false;
  }
  // extract the last characters of the string and substring 
  // using the substr method and compare them
  return str.substr(-sub.length) === sub;
};

// ๐Ÿงช TEST CASES
console.log(checkEnding("Congratulation", "on")); // true
console.log(checkEnding("Connor", "n")); // true
console.log(checkEnding("Walking on water", "walk")); // false
console.log(checkEnding("He has to give me a new name", "name")); // true
console.log(checkEnding("Open sesame", "same")); // true
console.log(checkEnding("Open sesame", "pen")); // false
console.log(checkEnding("Open sesame", "game")); // false

0

21.535

Check if String ends with Substring in JavaScript

JavaScript by Radu TM โ€ข June 22, 2022

// Check if a string (str) ends with a given substring (substr).

function checkEnding(str, substr) {
  // Get the length of the string.
  let len = str.length;

  // Get the length of the substring.
  let subLen = substr.length;

  // Compare the last characters of the string and the substring.
  // If they match, the string ends with the substring.
  if (str.substr(len - subLen, len) === substr) {
    return true;
  } else {
    return false;
  }
}

// Test the function

let str = "Hello, world!";
let substr = "world!";

console.log(checkEnding(str, substr)); // true

0

21.535

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories