settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Check if String ends with given Substring in JavaScript

+2 votes

Write a JavaScript function that checks if a given string, ends with a given substring.

The input comes as 2 string arguments:

  • The first string will represent the main one
  • The second one will represent the substring.

Examples:

Input:
This sentence ends with fun?
fun?

Output:
true


Input:
This is Houston, we have…
We have…

Output:
false


Input:
The new iPhone has no headphones jack.
o headphones jack.


Output:
true


The output is either “true” or “false” based on the result of the check. The comparison is case-sensitive!

asked in JavaScript category by user nikole

2 Answers

+2 votes

My javascript code:

function checkEnd(data, checkData) {
    let check = data.substr(data.length - checkData.length, data.length);

    if (check == checkData) {
        console.log(true);
    } else {
        console.log(false);
    }
}

//checkEnd("This sentence ends with fun?", "fun?");
checkEnd("This is Houston, we have…","We have…");

 

answered by user john7
0 votes

my code:

(text,substr)=>text.endsWith(substr);

 

answered by user Jolie Ann
...