前端js字符串首字母轉(zhuǎn)換成大寫(小寫)

// 判斷是否是字符串
isString(e) {
  let flag = typeof e === 'string'
  if (flag) {
    return e.trim()
  } else {
    return false
  }
},

// 轉(zhuǎn)換大小寫 toUpperCase  toLowerCase
changeString(e, type = 'toUpperCase') {
  let txt = isString(e)
  if (!txt) {
    console.error('參數(shù)不是字符串')
    return e
  }

  if (!/^[A-Za-z]/.test(txt)) {
    console.error('參數(shù)去收尾空格后第一個字符不是字母')
    return e
  }

  // 轉(zhuǎn)換大小寫參數(shù)錯誤默認(rèn)到轉(zhuǎn)成大寫
  if (type && !['toUpperCase', 'toLowerCase'].includes(type)) {
    type = 'toUpperCase'
  }

  let first = txt[0][type]()
  let newTxt = ''

  // 方法一:for遍歷
  for (let i = txt.length - 1; i > 1; i--) {
    newTxt = txt[i] + newTxt

    // 最后一次把首字母也拼進(jìn)去
    if (i === 1) newTxt = first + newTxt
  }


  // 方法二:截取后面的字符出來
  // let end = txt.slice(1)
  // let end = txt.substring(1)
  let end = txt.substr(1) // *ECMAscript沒有對該方法進(jìn)行標(biāo)準(zhǔn)化,因此反對使用它
  newTxt = first + end
  // slice、substring和substr的區(qū)別
  // slice(start, end)
  // substring(start, end)
  // substr(start, length)


  // 方法三:正則替換
  // newTxt = txt.replace(/^\S/, first)
  newTxt = txt.replace(/^\S/, s => s[type]())

  return newTxt
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容