最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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 

发布评论

评论列表(0)

  1. 暂无评论