js去除空格,手機號碼格式化處理方法

以下是一些常用的字符串處理方法:


// 去掉字符串中所有空格(包括中間空格,需要設置第2個參數爲:g)

function trim(str, is_global) {

  var result;

  result = str.replace(/(^\s+)|(\s+$)/g, "");

  if (is_global && is_global.toLowerCase() == "g") {

    result = result.replace(/\s/g, "");

  }

  return result;

}

 

// 判斷是否是手機號碼格式

function isPhone(str) {

  var reg = /^1(3|4|5|7|8)\d{9}$/;

  return reg.test(trim(str, 'g'));

}

 

// 手機號碼格式轉化爲 344 格式 (188 3886 9199)

function phoneSeparated(phoneNumber) {

  let tel = trim(phoneNumber, 'g');

  if (isPhone(tel)) {

    tel = tel.substring(0, 3) + ' ' + tel.substring(3, 7) + ' ' + tel.substring(7, 11);

  }

  return tel;

}


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章