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.
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.
3 Answers
Reset to default 7You 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.
if(s.matches("\\d.*\\d"))
{
// Do what you want once both start and ending characters are digits
}
This solution achieves the same result without a Regex. It also takes care of empty strings or strings with only one character.
function startsAndEndsWithDigits(string)
{
if(string.length>0)//if string is not empty
{
var firstChar = string.split('')[0];//get the first charcter of the string
var lastChar = string.split('')[string.length -1];//get the last charcter of the string
if(firstChar.length>0 && lastChar.length>0)
{ //if first and last charcters are numbers, return true. Otherwise return false.
return !isNaN(firstChar) && !isNaN(lastChar);
}
}
return false;
}
Usage example:
startsAndEndsWithDigits('1KJ25LP3665'); //returns true
startsAndEndsWithDigits('K12M25XC5750');//returns false
startsAndEndsWithDigits(''); //returns false
startsAndEndsWithDigits('a'); //returns false
startsAndEndsWithDigits('7'); //returns true
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743754807a4501562.html
评论列表(0条)