[js][字符串]給字符串去空格(全角和半角)


遇到問題

input框中輸入全角空格,提交時,使用以下方法並沒有被過濾,表單提交成功。

const removeSpace = function(str) {
  // 去除空格
  if (!str) {
    return ''
  } else {
    return str.replace(/\s/gi, '')
  }
}

解決方法

const removeSpace = function(str) {
  // 去除空格
  if (!str) {
    return ''
  } else {
    return str.replace(/(\s*)|(\s*$)/g, '')
  }
}

擴展--去除字符串首尾的空格

const removeSpace = function(str) {
  // 去除空格
  if (!str) {
    return ''
  } else {
    return str.replace(/(^\s*)|(\s*$)/g, '')
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM