- Instant help with your JavaScript coding problems

Check if a string ends with number in JavaScript

Question:
How to check if a string ends with number in JavaScript?
Answer:
const endsWithNumber = (text) => {
    return /\d$/.test(text);
}
Description:

If we want to check if a text ends in a number, we unfortunately cannot use the endsWith method because it only checks for a specific case. In this case, you need to check that the last character in the text is between 0 and 9. To solve this problem we can use a regular expression and the test method.

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.

In this case the regular expression is quite simple. We only need to check if the last character $ is a digit \d or not: /\d$/

Share "How to check if a string ends with number in JavaScript?"
Related snippets:
Tags:
string, text, ends, ends with, number, digit, chararcter, check, javascript
Technical term:
Check if a string ends with number in JavaScript