quiz icon indicating copy to clipboard operation
quiz copied to clipboard

JS基础测试41期

Open zhangxinxu opened this issue 4 years ago • 32 comments

本期关于手机号字符相关一些处理:

原图地址

每题1~2积分。

答题前不要看别人回答,答题后可以,但不能修改自己回答

大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式(1积分)。

```js
// 你的JS代码写在这里
 ```

其它:

  1. 首位答题者可获得直播翻牌机会;
  2. 本次答疑直播为12月07日上午10:00,预计25分钟;

zhangxinxu avatar Dec 04 '19 10:12 zhangxinxu

var strTel = '13208033621  ';
//1去掉前后空格
strTel.trim();
//2全角转半角
function toCDB(str){ 
    var tmp = ""; 
    for(var i=0;i<str.length;i++) 
    { 
        if(str.charCodeAt(i)>65248&&str.charCodeAt(i)<65375){ 
            tmp += String.fromCharCode(str.charCodeAt(i)-65248); 
        }else { 
            tmp += String.fromCharCode(str.charCodeAt(i)); 
        } 
    } 
    return tmp
}
toCDB(strTel);
//3.去掉前面的+86
strTel.replace(/^\+86/,'');
//4.去掉横杠或空格
strTel = '1320-8033-621';
strTel = strTel.replace(/(?!^)(-+|\s+)(?<!$)/g,'');
//5.验证是否合法
/^1\d{10}$/.test(strTel)

liyongleihf2006 avatar Dec 04 '19 11:12 liyongleihf2006

// 1
strTel.trim();

// 2
[..."0123456789"].reduce(
  (acc, cur, idx) => acc.replace(new RegExp(cur, "g"), idx),
  strTel
);

//3
strTel.replace(/^\+86/, "");

//4
strTel.match(/\d/g).length === 11 && strTel.replace(/-| /g, "");

//5
/^1\d{10}$/;

Seasonley avatar Dec 04 '19 12:12 Seasonley

// 第一题
strTel = strTel.trim()
// 第二题
let strTel = '1234567890'
let result = ''
for (var i = 0; i < strTel.length; i++) {
  let nCode = strTel.charCodeAt(i);    
  if (nCode >= 0xFF10 && nCode <= 0xFF19) {
    nCode = nCode - 65248
  }
  result += String.fromCharCode(nCode)
}
console.log(result)
// 第三题
strTel.replace(/^\+86/, '')
// 第四题
strTel.replace(/(\d{4})[\s-](\d{4})[\s-](\d{3})/g, '$1$2$3')
// 第五题
/^1\d{10}$/g.test(strTel)

asyncguo avatar Dec 04 '19 12:12 asyncguo

第一题

function getTel(numTel) {
  return numTel.trim();
};
var strTel = getTel(" 12308033621 ");
console.log({ strTel });

第二题

function getTel(numTel) {
  var objArray = {
    '0': 0,
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9
  };
  var strResult = '';
  for (var i = 0; i < numTel.length; i++) {
    var chartIt = objArray[numTel.charAt(i)];
    if (chartIt) {
      strResult += chartIt;
    }
  }
  return strResult;
};
var strTel = getTel("1 3 2 0 8 0 3 3 6 2 1 ");
console.log({ strTel });

第三题

function getTel(numTel) {
  var numTrim = numTel.trim();
  return numTrim.indexOf('+86') === 0 ? numTrim.slice(3) : numTrim;
};
var strTel = getTel("+8613208033621");
console.log({ strTel });

第四题

function getTel(numTel) {
  var strResult = '';
  for (var i = 0; i < numTel.length; i++) {
    var strCharIt = strTel.charAt(i);
    if (strCharIt > -1 && strCharIt < 10) {
      strResult += strCharIt;
    }
  }
  return strResult;
};
var strTel1 = getTel(" 1320-8033-621 ");
var strTel2 = getTel(" 1320 8033 621 ");
console.log({ strTel1, strTel2 });

第五题

function getIsValidate(numTel) {
  return /^1\d{10}$/.test(numTel);
};
var isValidate = getIsValidate("12208033621");
console.log({ isValidate });

ziven27 avatar Dec 04 '19 12:12 ziven27

测试demo

//1.
function toTrim(str){
    return str.trim();
}

//2.
function toCDB(str){
    return str.replace(/[\uff00-\uffff]/g,function($1){
        return String.fromCharCode($1.charCodeAt(0)-65248); 
    })
}

//3.
function removeCode(str){
    return str.replace(/^\+86/g,'');
}

//4.
function removeSpaceOrHyphen(str){
    return str.replace(/[\s-]+/g,'');
}

//5.
function testTel(str){
    return /^1\d{10}$/.test(str);
}

XboxYan avatar Dec 04 '19 12:12 XboxYan

第 1 题

function trimBlank(strTel) {
  return strTel.trim()
}

第 2 题

function doubleByteToSingle(strTel) {
  const doubleByteNums = '0123456789';
  return strTel.replace(
    new RegExp('[' + doubleByteNums + ']', 'g'), matched =>
      doubleByteNums.indexOf(matched)
  )  
}

第 3 题

function rmCountryCode(strTel) {
  return strTel.replace(/^\+8\s*6/, '')
}

第 4 题

function rmConnector(strTel) {
  return strTel.replace(/\D/g, '')
}

第 5 题

function isValidTel(strTel) {
  return /^1\d{10}$/.test(strTel);
}
测试用例
const tests = [
  { it: ' 13208033621  ', expect: '13208033621', handle: trimBlank },
  { it: '13208033621', expect: '13208033621', handle: doubleByteToSingle },
  { it: '+8613208033621', expect: '13208033621', handle: rmCountryCode },
  { it: '1320-8033-621', expect: '13208033621', handle: rmConnector },
  { it: '1320 8033 621', expect: '13208033621', handle: rmConnector },
  { it: ' +8  613 208-033621  ', expect: true, handle: isValidTel }
];

function trimBlank(strTel) {
  return strTel.trim()
}

function doubleByteToSingle(strTel) {
  const doubleByteNums = '0123456789';
  return strTel.replace(
    new RegExp('[' + doubleByteNums + ']', 'g'), matched =>
      doubleByteNums.indexOf(matched)
  )  
}

function rmCountryCode(strTel) {
  return strTel.replace(/^\+8\s*6/, '')
}

function rmConnector(strTel) {
  return strTel.replace(/\D/g, '')
}

function isValidTel(strTel) {
  return /^1\d{10}$/.test(
    rmConnector(
      rmCountryCode(
        doubleByteToSingle(
          trimBlank(strTel)
        )
      )
    )
  );
}

tests.map(test => {
  const result = test.handle(test.it);
  const isPassed = result === test.expect;

  console.group(`${test.it} -> ${test.expect}`);
    isPassed ?
      console.log('%c√ Pass', 'color: green') :
      console.log('%c× Failed! the actual result is: ' + result, 'color: red');
  console.groupEnd();
});

wingmeng avatar Dec 04 '19 13:12 wingmeng

    var strTel = ' +861725777577 '

    // 1
    function trim(str) {
      return str.trim()
    }

    // 2
    function allToHalf(str) {
      return Array.from(str).map((sub, index) => {
        let temp = sub.charCodeAt()
        if (temp >= 65281 && temp <= 65374) {
          temp -= 65248
          return String.fromCharCode(temp)
        } else {
          return sub
        }
      }).join('')
    }

    // 3
    function dealHeader(str) {
      return str.replace(/^\+86/, '')
    }

    // 4 zxx: 空格貌似没过滤
    function formatPhone(str) {
      let numCount = 0
      for (let i = 0; i < str.length; i++) {
        if (!isNaN(parseInt(str[i], 10))) {
          numCount++
        }
      }
      return numCount == 11 ? str.replace(/[-+\b+]/g, '') : str
    }


    // 5
    function isPhone(str) {
      return /^1\d{10}$/.test(str)
    }

les-lee avatar Dec 04 '19 14:12 les-lee

// 第一题
var strTel = '13208033621 '
strTel = strTel.trim()
console.log(strTel)

// 第二题
const toChangeHalf = str => str.replace(/[\uFF10-\uFF19]/g, (char) => char.charCodeAt() - 0xff10)
console.log(toChangeHalf('13208033621'))

// 第三题
const withOutx86 = str => str.replace(/^\+86/, '')
console.log(withOutx86('+8613208033621'))

// 第四题
const withOutLine = str => {
  const numCount = str.split('').reduce((res, v) => {
    if (/\d/.test(v)) {
      res++
    }
    return res
  }, 0)
  if (numCount === 11) {
    return str.replace(/\s|\-/g, '')
  }
}
console.log(withOutLine('1354-4007-502'))


// 第五题
const validTel = str => /^1\d{10}$/.test(str)
console.log(validTel('13208033621'))
console.log(validTel('23544007502'))



console.log(validTel(withOutLine(withOutx86(toChangeHalf('+861320-8033-621 '.trim())))))

livetune avatar Dec 04 '19 14:12 livetune

var strTel = "10 1 2 3 4 5 6 7 8 9 . .";
// 1
strTel.trim();
// 2
var toHalfStr = "";
var length = strTel.length;
for (let i = 0; i < length; i++) {
  var charCode = strTel.charCodeAt(i);
  if (charCode > 65280 && charCode < 65375) {
    toHalfStr += String.fromCharCode(charCode - 65248);
  } else if (charCode === 12288) {
    // 全角空格
    toHalfStr += String.fromCharCode(32);
  } else {
    toHalfStr += String.fromCharCode(charCode);
  }
}
strTel = toHalfStr;
// 3
// 或者 strTel = strTel.replace("+86", "");
strTel = strTel.replace(/^\+86/, "");
// 4 在数字个数符合手机号码的情况下
if (strTel.match(/\d/) && strTel.match(/\d/g).length === 11) {
  strTel = strTel.replace(/\D/g, "");
}
// 5
var telReg = /^1\d{10}$/;

Despair-lj avatar Dec 04 '19 16:12 Despair-lj

// 1

    function handleTrim (str) {
      return str.trim()
    }

// 2

    function handleToCDB (str) {
      var Reg = /[\uff00-\uffff]/g
      return str.replace(Reg, (mate) => {
        return String.fromCharCode(mate.charCodeAt()-65248)
      })
    }

// 3

    function removeCode(str){
      return str.replace(/^\+86/g,'');
    }

// 4

    function removeBlankSumHyphen (str) {
      return str.replace(/[\s-]+/g, '')
    }

// 5

    function handlePhoneNumber (str) {
      var reg = /^1\d{10}$/;
      return reg.test(str)
    }

zengqingxiao avatar Dec 04 '19 16:12 zengqingxiao

strTel.trim()
strTel.split('').map(v => v.charCodeAt() > 65248 ? String.fromCharCode(v.charCodeAt() - 65248) : v).join('');
strTel.replace(/^\+86([0-9]{11})$/, function(v, g) {return g;});
//zxx: 有点意思
strTel.replace(/^[0-9]([ -]?[0-9]){10}$/, function(v) {
	return v.replace(/[ -]/g,'');
});
/^1[0-9]{10}$/

NeilChen4698 avatar Dec 04 '19 16:12 NeilChen4698

 // 第一题
strTel = strTel.trim()
// 第二题
strTel = strTel.split('').map(item => {
    let temp = ''
    if (item.charCodeAt() === 12288) {
        temp += String.fromCharCode(item.charCodeAt() - 12256)
    }
    if (item.charCodeAt() > 65280 && item.charCodeAt() < 65375) {
        temp += String.fromCharCode(item.charCodeAt() - 65248)
    } else {
        temp += String.fromCharCode(item.charCodeAt())
    }
    return temp
}).join('')
// 第三题
strTel = strTel.replace(/^\+86/, '')
// 第四题
//zxx: 不符合应该是空字符串,而是还是strTel哦~
strTel = strTel.replace(/[-\s]/g, '').length === 11 ? strTel.replace(/[-\s]/g, '') : ''
// 第五题
let reg  = /^1\d{10}$/g
strTel = reg.test(strTel) ? strTel : ''

LYN-alan avatar Dec 05 '19 02:12 LYN-alan

            let strTel = "  13208033621  "
            let dict = {
                "0": 0,
                "1": 1,
                "2": 2,
                "3": 3,
                "4": 4,
                "5": 5,
                "6": 6,
                "7": 7,
                "8": 8,
                "9": 9,
            }

            //1
            strTel = strTel.trim();
            console.log(strTel);

            //2
            strTel = "   1 3 2 0 8 0 3 3 6 2 1   ";
            strTel = strTel.trim().replace(/[0123456789]/g, key => dict[key]).replace(/\s+/g, "");
            console.log(strTel);

            //3
            strTel = "+8613208033621";
            strTel = strTel.replace(/^\+86/, "");
            console.log(strTel);

            //4
            // strTel = "1320-8033-621";
            strTel = "1320  8033  621";
            strTel = strTel.replace(/-|\s+/g, "")
            console.log(strTel)

            //5
            strTel = "13208033621"
            let reg = /^1\d{10}$/;
            let checkResult = reg.test(strTel);
            console.log(checkResult);

guqianfeng avatar Dec 05 '19 02:12 guqianfeng

/**
 * 检测手机号码的合法性
 * @param {string} phone 用户输入的手机号码
 */
function isPhoneNumber (phone) {
  // 第一题:去除前后空格
  let number = phone.trim()
  // 第二题:将全角字符转为半角字符
  number = number.replace(/[\uFF00-\uFFFF\u3000]/g, s => {
    let code = s.charCodeAt(0)
    // 全角空格单独处理
    return code === 12288 ? ' ' : String.fromCharCode(code - 65248)
  })
  // 第三题:去掉开头的+86
  number = number.replace(/^\+86/, '')
  // 第四题:匹配数字个数,去除中间短横线或空格
  if (number.replace(/[\D]/g, '').length === 11) {
    number = number.replace(/[\-\s]/g, '')
  }
  // 第五题:检测手机号码格式是否正确
  return /^1[\d]{10}/.test(number)
}

let case1 = '13393939122'
let case2 = ' 133-9393-9122  '
let case3 = ' 13s-9393-9122'
let case4 = ' 134 3458 8475 '
let case5 = ' +86 133-9393-9122'

console.log(isPhoneNumber(case1))
console.log(isPhoneNumber(case2))
console.log(isPhoneNumber(case3))
console.log(isPhoneNumber(case4))
console.log(isPhoneNumber(case5))

xxf1996 avatar Dec 05 '19 03:12 xxf1996

// 1
strTel = strTel.trim()

// 2
strTel = toCDB(strTel)
function toCDB(str) {
  var tmp = '';
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) {
      tmp += String.fromCharCode(str.charCodeAt(i) - 65248)
    }
    else {
      tmp += String.fromCharCode(str.charCodeAt(i))
    }
  }
  return tmp
}

// 3
strTel = strTel.replace(/^\+86/, '')

// 4
strTel = strTel.replace(/[^0-9]+/g, '').length === 11 ? strTel.replace(/[^0-9]+/g, '') : strTel

// 5
/^1\d{10}$/g

JaimeCheng avatar Dec 05 '19 03:12 JaimeCheng

第一题

strTel.trim();

第二题

//zxx: 只有+86才替换哦~
// 替换+号和两位数字开头
strTel.replace(/^(\+\d{2})/, '');

第三题

 //  '0'.charCodeAt() - '0'.charCodeAt() = 65248,使用String.fromCharCode()获取半角数字
strTel.replace(/[\uFF10-\uFF19]/g, $ => String.fromCharCode($.charCodeAt() - 65248));

第四题

// 先判断strTel中数字长度是否是11,是的话去掉空格,短横
if(strTel.match(/\d/g).length === 11) {
 strTel = strTel.match(/\d/g).join('');
}

第五题

/^1\d{10}/.test(strTel);

uaison avatar Dec 05 '19 06:12 uaison

function strTelF1(strTel){
//1、
 return strTel.trim();
//2、
 return strTel.replace(/(^\s*)|(\s*$)/g,'');
}
function strTelF2(strTel){
	//var obj=strTel.match(/[\uff00-\uffff]/g)//全角 ;
//全角空格为12288,半角空格为32 ;
//其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
return strTel.replace(/[\uff00-\uffff]/g,function(ele){
      return String.fromCharCode(ele.charCodeAt(0)-65248); 
   })
}
function strTelF3(strTel){
	return strTel.replace(/^\+86/g,'');
}
function strTelF4(strTel){
	return strTel.replace(/(-*)(\s*)/g,'');
}
function strTelF5(strTel){
	var test1=/^1\d{10}$/;
	return test1.test(strTel);
}
console.log('1、',strTelF1(' 1231234567 '));
console.log('2、',strTelF2('1;,236545'));
console.log('3、',strTelF3('+8612312345671'));
console.log('4、',strTelF4('123-1234-5670'));
console.log('5、',strTelF5('13212345671'));

WGHwebitem avatar Dec 05 '19 07:12 WGHwebitem

//第1题
let strTel1 = '13208033621 ';
strTel1 = strTel1.replace(/(^\s*)|(\s*$)/g, "");

//第2题
//zxx: 只有全角才变化哦,不是任意字符哟~
let strTel2 = '13208033621';
let newStrTel = change(strTel2);

function change(strTel) {
    let newNum = '';
    for(let i=0; i<strTel.length; i++) {
        newNum = newNum + String.fromCharCode(strTel.charCodeAt(i)-65248)
    }
    return newNum;
}

//第3题
let strTel3 = '+8613208033621';
let re3 = /^\+86/g;
strTel3 = strTel3.replace(re3,'');

//第4题
let strTel4 = '132-0803 3621';
let re4 = /\s|-/g;
strTel4 = strTel4.replace(re4, '');

//第5题
let re5 = /^1[0-9]{10}/g;

HaveYuan avatar Dec 05 '19 12:12 HaveYuan

// 第一题
function strTrim(str) {
    return str.trim()
}
console.log(strTrim(' 13208033621 '));

// 第二题
function strDoubleByte(str) {
    const doubleByte = '0123456789';
    let strTel = ''
    return doubleByte.split('').reduce((str, number, index) => {
        // 找到id
        return str.replace(new RegExp(number, 'g'), index)
    }, str);
}
console.log(strDoubleByte('13208033621'));

// 第三题
function strRemove86(str) {
    // 应该要是11位的
    return str.replace(/^\+86/, '');
}
console.log(strRemove86('+8613208033621'));

// 第四题
function strRemoveD(str) {
    return str.replace(/\D/g, '')
}
console.log(strRemoveD('1320-8033 621'));   

// 第五题
function strValid(str) {
    return /^1\d{10}$/.test(str);
}
console.log(strValid('13208033621'));

rayj1993 avatar Dec 05 '19 14:12 rayj1993

var strTel = '13208033621  ';
strTel = strTel.replace('/\s/g, '')
function ToCDB(str) { 
    var tmp = ""; 
    for(var i=0;i<str.length;i++){ 
        if (str.charCodeAt(i) == 12288){
            tmp += String.fromCharCode(32);
            continue;
        }
        if(str.charCodeAt(i) > 65280 && str.charCodeAt(i) < 65375){ 
            tmp += String.fromCharCode(str.charCodeAt(i)-65248); 
        } 
        else{ 
            tmp += String.fromCharCode(str.charCodeAt(i)); 
        } 
    } 
    return tmp 
} 

function formatPhone(phone) {
    const len = phone.length
    if (len > 11 ) {
          return phone.slice(len - 11 + 1)
     } else {
         return phone
    }
}
strTel= strTel.replace(/(-|\s)/g, '')
var reg = /^1\d{10}$/
console.log(reg.test(strTel)

flyinglove avatar Dec 06 '19 00:12 flyinglove

  • 第一题
//zxx: 只有首尾空格要去除哦~
function clearBlank(strTel) {
   return strTel.replace(/\s/g, "");
}
  • 第二题
function ToCDB(strTel) {
    var tmp = "";
    for (var i = 0; i < strTel.length; i++) {
        if (strTel.charCodeAt(i) > 65248 && strTel.charCodeAt(i) < 65375) {
            tmp += String.fromCharCode(strTel.charCodeAt(i) - 65248);
        } else {
            tmp += String.fromCharCode(strTel.charCodeAt(i));
        }
    }
    return tmp
}
  • 第三题
function clear86(strTel) {
   return strTel.replace(/^\+86/g, "");
}
  • 第四题
function clearLineAndBlank(strTel) {
    return strTel.replace(/\s|-/g, "");
}
  • 第五题
function checkLegal(strTel) {
    return (/^[1][0-9]{10}$/.test(strTel));
}
console.log(clearBlank('13208033621  '));
console.log(ToCDB('1234567890'));
console.log(clear86('+8613208033621'));
console.log(clearLineAndBlank('1320-8033-621'));
console.log(clearLineAndBlank('1320 8033 621'));
console.log(checkLegal('13208033621'));

lifelikejuly avatar Dec 06 '19 01:12 lifelikejuly

// 1. 去掉前后空白符
'\t13208033621  '.trim()

// 2. 全角转半角
// '0'.charCodeAt(0) // 65296
// '1'.charCodeAt(0) // 65297
// '9'.charCodeAt(0) // 65305
// '0'.charCodeAt(0) // 48
// '9'.charCodeAt(0) // 57
function f2h(tel) {
    // 不考虑出现其他字符 纯数字
    var str = tel.trim()
    var res = []
    for (let i = 0; i < str.length; i++) {
        let code = str.charCodeAt(i)
        if (code >= 65296 && code <= 65305) {
            // 是全角字符的数字
            res.push(String.fromCharCode(code - 65248))
        } else {
            res.push(str[i])
        }
    }
    return res.join('')
}
console.log(f2h('1234567890'))
console.log(f2h('1234567890'))

// 3. 去掉+86
'+8613208033621'.trim().replace(/^\+86/, '')

// 4. 去掉短横线或者空格
function removeDelimiter(tel, delimiter = [/-/, /\s/]) {
    // 先判断数字个数
    return tel.match(/\d/g).length === 11 && delimiter.reduce((init, next) => {
        var reg = new RegExp(next, 'g')
        return init.replace(reg, '')
    }, tel)
}
console.log(removeDelimiter('132-0   803-3621'))

// 5. 第一个字符为1的 11位纯数字

console.log((/^1[0-9]{10}/).test('13208033621'))

ylfeng250 avatar Dec 06 '19 02:12 ylfeng250

demo

var strTel = '+8613208033621 ';
//清除前后空格
function blankTrim(str){
  return str.trim()
}
console.log('清除前后空格---- ',blankTrim(strTel))

// 全角转半角
function halfTransfrom(str){
  return str.replace(/[\uFF00-\uFFFF]/g,function($1){
	return String.fromCharCode($1.charCodeAt() - 65248)
  })
}

console.log('半角转换---- ',halfTransfrom('0123456789'));

//去+86
function removes(str){
  return str.replace(/^\+?86/,'');
}
console.log('去86---- ',removes(strTel))

//去短横线或者空格
function normalTel(str){
  let mob = str.replace(/(-|\s?)/g,'');
  return mob.length === 11 ? mob : '手机号码错误';
}
console.log('去短横线',normalTel('1320-8033-621'))
console.log('去空格',normalTel('1320 8033   1'))
console.log('去空格',normalTel('1320 8033   111'))


// 是否合法手机
function telValidity(str){
  return /^1[0-9]{10}$/.test(str) ? str :'手机格式错误';
}
console.log('错误示例:',telValidity(strTel));
console.log('正确示例:',telValidity('13208033621'));

juzhiqiang avatar Dec 06 '19 03:12 juzhiqiang

let strTel = ' +86 132-0803-3621  ';

// 首尾空格
let tel = strTel.replace(/(^\s+|\s+$)/g, '');

// 全角转半角
tel = tel.replace(/[\uff10-\uff19]/g, (s) => s.charCodeAt() - 0xff10);

// 去除+86前缀
tel = tel.replace(/^\+86/g, '');

// 判断位数是否符合要求 tel.match(/[0-9]/g).length === 11
// 去除多余空格、横线
tel = tel.replace(/(\s|-)/g, '');

// 验证手机号
/^1[0-9]{10}$/.test(tel);

kscript avatar Dec 06 '19 03:12 kscript

// 1. 去除字符前后的空格
var strTel = '13208033621  '
var result_1 = strTel.trim()
console.log('----------第1题---------', result_1)

// 2
//zxx: 可以可以
var strTel = '13208033621'
var n = '0123456789'
var result_2 = strTel.replace(/[0-9]/g, item => n.indexOf(item))
console.log('----------第2题---------', result_2)

// 3
var strTel = '+8613208033621'
var result_3 = strTel.replace(/^\+86/g, '')
console.log('----------第3题---------', result_3)

// 4
var strTel_1 = '1320-8033-621'
var strTel_2 = '1320 8033  621'
function formatSpace(strTel) {
  return strTel.match(/[0-9]/g).length === 11 && strTel.replace(/[-\s]/g, '') || strTel
}
var result_4_1 = formatSpace(strTel_1)
var result_4_2 = formatSpace(strTel_2)
console.log('----------第4题---------', result_4_1, result_4_2)

// 5
var strTel = '13208033621'
var result_5 = /^1[0-9]{10}$/.test(strTel)
console.log('----------第5题---------', result_5)

zy017 avatar Dec 06 '19 05:12 zy017

function trim(str){
    return str.trim();
}
function ToCDB(str) {
    var res = "";
    for(var i=0;i<str.length;i++){
        if (str.charCodeAt(i) === 12288){
            res += String.fromCharCode(str.charCodeAt(i)-12256);
            continue;
        }
        if(str.charCodeAt(i) > 65280 && str.charCodeAt(i) < 65375){
            res += String.fromCharCode(str.charCodeAt(i)-65248);
        }
        else{
            res += String.fromCharCode(str.charCodeAt(i));
        }
    }
    return res;
}
function splitCode(str){
    return str.replace(/\+86/g,'');
}
function splitStr(str){
    return str.replace(/[\s-]/g,'');
}
function validateTel(str){
    return /^1\d{10}$/.test(str);
}
console.log(trim('13164621126 '));
console.log(ToCDB('13164621126'));
console.log(splitCode('+8613164621126'));
console.log(splitStr('1316 4621 126'));
console.log(splitStr('1316-4621-126'));
console.log(validateTel('13164621126'));

silverWolf818 avatar Dec 06 '19 06:12 silverWolf818

var strTel = " 13208033621 "
console.log(strTel.trim())
//zxx:  不是所有字符都要变化哟~
var strTel = "13208033621" 
strTel = strTel.split('').map(s=> String.fromCharCode(s.charCodeAt(0)-65248)).join('')
console.log(strTel)
var strTel = "+8613208033621"
strTel = strTel.replace(/^(\+86)(\d{11})$/,'$2')
console.log(strTel)
var strTel = "1320-8033-621"
strTel = strTel.replace(/([^\d]*)/g,'')
console.log(strTel)
var strTel = "13208033621"
console.log(/^1\d{10}$/.test(strTel))

kuikuiGe avatar Dec 06 '19 13:12 kuikuiGe

function trim(str) {
    return str.trim()
}
function toSemiangle(str) {
    return str.replace(/[\uFF10-\uFF19]/g, $ => String.fromCharCode($.charCodeAt() - 65248))
}
function dropCode(str) {
    return str.replace(/^\+86/g,'')
}
function dropSeparator(str) {
    return str.replace(/\D/g, '')
}
function isLegalPhoneNum(str) {
    return /^1\d{10}$/.test(str)
}

frankyeyq avatar Dec 06 '19 13:12 frankyeyq

第一题

// 去掉前后的空格
let strTel = '  13208033621   ';
strTel = strTel.trim();

第二题

// 全角变半角
let strTel = '13208033621';
function change(str) {
  const reg = /[\ufe30-\uffa0]/g;
  return str.replace(reg, (match) => String.fromCharCode(match.charCodeAt()  - 65248));
}
strTel = change(strTel);

第三题

let strTel = '+8613208033621';
// 去掉前面的+86
strTel = strTel.indexOf('+86') === 0 ? strTel.slice(3) : strTel;

第四题

// 去掉中间的短横线或者空格
let strTel = '1320-8033-621';
const reg = /(?<=\d+)(\-|\s)+(?=\d+)/g;
strTel = strTel.replace(reg, '');

第五题

// 验证是否合法
let strTel = '12208033623';
const reg = /^[1]\d{10}$/;
console.log(reg.test(strTel));

zjgyb avatar Dec 06 '19 14:12 zjgyb

第一题

strTel = strTel.trim()

第二题

function ToCDB(str) {
  var tmp = "";
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) == 12288) {
      tmp += String.fromCharCode(str.charCodeAt(i) - 12256);
      continue;
    }
    if (str.charCodeAt(i) > 65280 && str.charCodeAt(i) < 65375) {
      tmp += String.fromCharCode(str.charCodeAt(i) - 65248);
    } else {
      tmp += String.fromCharCode(str.charCodeAt(i));
    }
  }
  return tmp
}
strTel=ToCDB(strTel)

第三题

let reg = /\+86/;
strTel = strTel.replace(reg, "")

第四题

let reg1 = /[\.-\s]*/g
strTel = strTel.replace(reg1, "")

第五题

let reg2 = /^1\d{10}$/
reg2.test(strTel)

sghweb avatar Dec 06 '19 14:12 sghweb