Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex ensure string starts and ends with digits

How do I write a regular expression for use in JavaScript that'll ensure the first and last characters of a string are always digits?

r = /\D+/g;
var s = "l10ddd31ddd5705ddd";
var o = r.test(s);
console.log(o);

So, 1KJ25LP3665 would return true, while K12M25XC5750 would return false.

like image 761
jmenezes Avatar asked Dec 18 '25 21:12

jmenezes


1 Answers

You can have a regex like below:

 /^\d(.*\d)?$/
  • The ^ to begin match from start of the string and $ to continue match till end of the string.
  • \d to match a digit at the beginning and the end.
  • .* to match zero or more characters in between.
  • We make the group 1 => (.*\d) optional with the ? metacharacter to optionally match zero or more characters ending with the digit till the end of the string. This would help if the string has only a single digit.
like image 76
nice_dev Avatar answered Dec 21 '25 10:12

nice_dev