Skip to main content

How to Check if a String Starts or Ends with a Number in JavaScript

When parsing filenames, processing user input, or validating data, you often need to check if a string begins or ends with a numeric character. The most powerful and flexible tool for this job in JavaScript is a regular expression.

This guide will teach you how to use the test() method of a regular expression to quickly determine if a string starts or ends with a number. You will also learn the key regex anchors and characters needed to perform these checks effectively.

Core Method: Regular Expressions with test()

A regular expression (regex) is a pattern used to match character combinations in strings. The RegExp.prototype.test() method executes a search for a match between a regex and a specified string, returning true or false.

The Key Regex Components:

  • /.../: The forward slashes enclose the regular expression pattern.
  • \d: A special character that matches any digit from 0 to 9. This is a shorthand for the character set [0-9].
  • ^: The start anchor. This asserts that the pattern must match at the very beginning of the string.
  • $: The end anchor. This asserts that the pattern must match at the very end of the string.

By combining these, we can build simple and highly readable tests.

How to Check if a String Starts with a Number

To check if a string starts with a number, we use the start anchor (^) followed by the digit matcher (\d).

Problem: we need to validate if a string begins with a numeric character.

// Problem: Does the string start with a digit?
const str1 = '456 avocado'; // Should be true
const str2 = 'avocado 123'; // Should be false

Solution: the regex /^\d/ means "match a digit at the start of the string."

function startsWithNumber(str) {
return /^\d/.test(str);
}

// Example Usage:
console.log(startsWithNumber('456 avocado')); // Output: true
console.log(startsWithNumber('avocado 123')); // Output: false
console.log(startsWithNumber('')); // Output: false

The test() method returns a simple boolean, making it perfect for conditional logic.

How to Check if a String Ends with a Number

To check if a string ends with a number, we use the digit matcher (\d) followed by the end anchor ($).

Problem: we need to validate if a string has a number at the very end.

// Problem: Does the string end with a digit?
const str1 = 'file-version-2'; // Should be true
const str2 = '3-file-version'; // Should be false

Solution: the regex /\d$/ means "match a digit at the end of the string."

function endsWithNumber(str) {
return /\d$/.test(str);
}

// Example Usage:
console.log(endsWithNumber('file-version-2')); // Output: true
console.log(endsWithNumber('3-file-version')); // Output: false
console.log(endsWithNumber('version-')); // Output: false

Sometimes you don't just want to check if a number exists; you want to extract it. You can do this with the String.prototype.match() method and a slightly modified regex.

The logic is about adding the + quantifier to our regex, which means "match the preceding item one or more times."

  • /^\d+/: Match one or more digits at the start of the string.
  • /\d+$/: Match one or more digits at the end of the string.

The match() method returns an array of matches or null if no match is found.

Solution:

function getNumberAtStart(str) {
const match = str.match(/^\d+/);
// If a match is found, match[0] contains the matched string.
return match ? Number(match[0]) : null;
}

function getNumberAtEnd(str) {
const match = str.match(/\d+$/);
return match ? Number(match[0]) : null;
}

// Example Usage:
console.log(getNumberAtStart('456 avocado')); // Output: 456
console.log(getNumberAtStart('avocado 123')); // Output: null

console.log(getNumberAtEnd('version-123')); // Output: 123
console.log(getNumberAtEnd('version-abc')); // Output: null

Conclusion

Regular expressions are the definitive tool for checking if a string starts or ends with a number. The test() method provides a quick and readable boolean result, perfect for validation.

  • To check if a string starts with a number, use the regex /^\d/.
  • To check if a string ends with a number, use the regex /\d$/.
  • To extract the number, use the match() method with the + quantifier (e.g., /^\d+/ or /\d+$/).

By mastering these simple patterns, you can handle a wide variety of string validation and parsing tasks with ease.