wingmeng / front-end-quiz

前端小测试答题收集
0 stars 0 forks source link

JS基础测试41:手机号字符处理 #40

Open wingmeng opened 4 years ago

wingmeng commented 4 years ago

题目:

0 原图

我的回答:

第 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);
}
测试用例
```js 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(); }); ```