To check if a string ends with a specific string or a word, you can use the endsWith()
string method in JavaScript.
Consider this string Hello, How are you?
,
// a string
const str = "Hello, How are you?";
Let's check to see if the string ends with the character ?
using the endsWith()
string method.
// a string
const str = "Hello, How are you?";
// check if string ends with character "?"
const doesIt = str.endsWith("?");
console.log(doesIt); // true
We can also check to see if it ends with a specific word and not a single character like above. For example, we can check to see if it ends with a word called you?
// a string
const str = "Hello, How are you?";
// check if the string ends with the string "you?"
const doesIt = str.endsWith("you?");
console.log(doesIt); // true
Another cool thing with this method is that you can define the end of the string instead of the default length of the string. For example, in the above example what if we don't need to check till the ?
character and only need to check if the string ends with the word you
.
You can do that by passing the length up to which you need to check as the second argument.
Here we don't need to check till the character ?
. So let's pass the length subtracted by one index as the second argument to the method like this,
// a string
const str = "Hello, How are you?";
// check if string ends with the string "you"
const doesIt = str.endsWith("you", str.length - 1);
console.log(doesIt); // true
See this example live in JSBin.
Key takeaways:
- the method accepts a string to check if it's present at the end as the first argument.
- the method accepts an optional length parameter to define the ending point for the string. If nothing is provided as the second argument, it defaults to the
length
property of the string. - the method returns a boolean
true
if string present at the end andfalse
if not.