js對(duì)字符串的常見(jiàn)操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

  /*
  1,charAt 返回指定位置字符
  2,concat 連接字符串
  3,indexOf 是否包含某個(gè)字符
  4,replace 替換指定字符串
  5,split 分割字符串
  6,slice 截取字符串
  7,substr  截取字符串
  8,substring  截取字符串
   */
    let str="hello,word";
    document.write(str.charAt(0)+"<br>");//返回指定位置的字符     charAt(index)
    document.write(str.concat("67")+"<br>");//連接2個(gè)字符串,通常用“+”更方便
    document.write(str.indexOf("w")+"<br>");//找出字符串中是否包含某個(gè)字符,不包含返回-1,包含返回第一個(gè)的下標(biāo)位置
    document.write(str.replace(/h/,"p")+"<br>");//替換字符,第一個(gè)參數(shù)可以是正則表達(dá)式
    console.log(str.split(","));//用于分割字符串為數(shù)組返回
    console.log(str.split("o",1));//分割結(jié)束只取數(shù)組中一個(gè)數(shù)據(jù)
   document.write(str.toLocaleUpperCase()+"  "+str.toLocaleLowerCase()+"<br>")
   document.write("--------以下是3種截取字符串的辦法-------------"+"<br>")
         /*
         1,slice和substring和substr 都是字符串截取,看個(gè)人愛(ài)好用那個(gè),slice
         document.write(str.slice(0,-4)+"<br>");//用于截取下標(biāo)取出字符串;返回。
         */
    document.write(str.substr(2,1)+"<br>");//第一個(gè)參數(shù)是下標(biāo)起始位置,第二個(gè)參數(shù)是后面要返回的長(zhǎng)度
    document.write(str.slice(0,4)+"<br>");//用于截取下標(biāo)取出字符串;返回。
    document.write(str.substring(2,1)+"<br>");//小的是起位置,大的末位置

</script>
</body>
</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容