首页 > 解决方案 > is there a way to check if a string is of this *x.xx.xxxx* format in JavaScript?

问题描述

I want a function to check if a string is of format x.xx.xxxx in javascript. For example, s.xf.ssfs should return true. And sx.xf.hsdf should return false. Also s.fsd.sfdf should return false.

标签: javascriptregexstring

解决方案


您可以尝试使用正则表达式:

const regex = new RegExp('[a-z][.][a-z]{2}[.][a-z]{4}');

console.log(regex.test('s.xf.ssfs'));
console.log(regex.test('s.fsd.sfdf'));

作为替代方案,您还可以按句点拆分字符串并检查每个项目的长度:

function check(s){
  let a = s.split('.');
  return a.length == 3 && a[0].length == 1 && a[1].length == 2 && a[2].length == 4;
}
console.log(check('s.xf.ssfs'));
console.log(check('sx.xf.hsdf'));


推荐阅读