首页 > 其他分享 >【JS】查验电话号码(fCC)

【JS】查验电话号码(fCC)

时间:2022-11-20 05:22:06浏览次数:51  
标签:查验 return else fCC str strB join JS match

题目要求查验电话号码是否输入正确,总结来说,需要满足以下条件:

  1. 号码中的数字应该在10-13个之间
  2. 不包含()-以外的符号
  3. ()要完整
  4. 可以有空格
  5. 如果最前面加了国家编号,限定编号为1

 

 

关键点:

1 正则表达式

2. 字符串方法string.join('')

可以将.match()得到的数组转换回字符串。

3.可选链运算符(?.)

可选链运算符(?.)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。

 

添加?后,变成const strB = strNS.match(/[()]/g)?.join('');就不会报错了。

 

实现代码:

function telephoneCheck(str) {
  //排除str中的空格
  const strNS = str.match(/\S/ig).join('');
  //str中的数字
  const allNum = str.match(/\d/ig).join('');
  //排除str中的空格和()
  const strNSB = strNS.match(/-*\d-*/g).join('');


  const strB = strNS.match(/[()]/g)?.join('');
  
  console.log(strB);
  console.log(strB === null );
  console.log(strNSB.match(/^1[1-9]{3}-*\d{3}-*\d{4}/g))


  if (strB ==='()'){
    if (allNum.length === 10) {
      return strNSB.match(/^[1-9]{3}-*\d{3}-*\d{4}/g) !== null;
    } else if (allNum.length === 11) {
      return strNSB.match(/^1[1-9]{3}-*\d{3}-*\d{4}/g) !== null;
    }else {
    return false;}
  } else if (strB === undefined) {
    if (allNum.length === 10) {
      return strNSB.match(/^[1-9]{3}-*\d{3}-*\d{4}/g) !== null;
    } else if (allNum.length === 11) {
      return strNSB.match(/^1[1-9]{3}-*\d{3}-*\d{4}/g) !== null;
    }else {
    return false;}
  } else {
    return false;
  }
}


console.log(telephoneCheck("-1 (757) 622-7382"));

 

 

标签:查验,return,else,fCC,str,strB,join,JS,match
From: https://www.cnblogs.com/mtlog/p/16907831.html

相关文章

  • js 事件循环中宏任务和微任务执行顺序
    asyncfunctionasync1(){console.log("async1start");//2awaitasync2();console.log("async1end");//6}asyncfunctionasync2(){console......
  • Node.js学习随笔
    Node.jsNode.js不是JS,但是和JavaScript的语法非常相似,是一种服务器端技术,他的竞争对手PHP/JAVA/C++/C#/PYTHON-历史上第一次一门语言可以通吃前后端-前端崛起原因之......
  • js一键通关
    1.typeof运算符和instanceof运算符以及isPrototypeOf()方法的区别typeof是一个运算符,用于检测数据的类型,比如基本数据类型null、undefined、string、number、boolean,以及......
  • js undefined null 区别
    在JavaScript中存在这样两种原始类型:Null与Undefined。这两种类型常常会使JavaScript的开发人员产生疑惑,在什么时候是Null,什么时候又是Undefined?Un......
  • js 右下角动态提示消息框
    js:varsheyMsg=function(box,options){this.box=this.g(box);this.setOptions(options);this.init();}sheyMsg.prototype={ae:function(e......
  • js cookie 操作
    functiongetCookie(name)...{varvalue=document.cookie;vararr1=value.split(";");for(i=0;i<arr1.length;i++)...{if(value.length=......
  • js实现树的存储和遍历
    树的概念:树这样的结构挺起来十分的吓人,实际上非常的简单,树是由一个个节点组成A//\\BCDE//\FGH我们使用数组来存储......
  • JS数据类型与对象
    <!DOCTYPEhtml><html><head><metacharset="utf-8"><title></title></head><body><!--数据类型与对象--><script>......
  • js输出、弹窗
    <!DOCTYPEhtml><html><head><metacharset="utf-8"><title></title><script>window.alert("弹窗");//document.get......
  • JS语法语句、变量
    <!DOCTYPEhtml><html><head><metacharset="utf-8"><title></title></head><body><!--语法与语句,变量--><!--......