javascript - regex ensure string starts and ends with digits - Stack Overflow

How do I write a regular expression for use in JavaScript that'll ensure the first and last charac

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.

Share Improve this question edited Jan 26, 2020 at 3:54 jmenezes asked Jan 26, 2020 at 3:48 jmenezesjmenezes 1,9368 gold badges28 silver badges50 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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.
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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信