javascript中的字符串編碼、字符串方法詳解


js中的字符串是一種類數組,采用UTF-16編碼的Unicode字符集,意味字符串的每個字符可用下標方式獲取,而每個字符串在內存中都是一個16位值組成的序列。js對字符串的各項操作均是在對16位值進行操作,而非字符。

在js中“\”后面的第一個字符不會被解析為字符,這就是js的轉義字符:

\o         NUL字符
\b         退格符
\t          水平制表符
\n         換行符
\v         垂直制表符
\f          換頁符
\r          回車符
\“          雙引號
\'           撇號或單引號
\\           反斜線
\xXX         由兩位十六進制數xx指定的latin-1字符
\uXXXX         由四位十六進制數XXXX指定的Unicode字符
    var str="pomelott is good\nyes he is !";
    console.log(str1);

控制台輸出如下:

pomelott is good
yes he is !

js常用字符串方法用法詳解:

    var s="hellow,pomelott";
    console.log(s.charAt(0));  //h
    console.log(s.charAt(s.length-1));  //t
    //substring(開始,結束)
    // 1.從下標1開始(包括)到下標4結束(不包括)
    //2. substring()參數不支持負數
    console.log(s.substring(1,4));   //"ell"
    ///slice(起始,結束)
    //1. 若起始位數字為負數,則從倒數開始;
    //2.結束位數字可選,缺省表示從開始為到字符串末尾切割
    console.log(s.slice(1,4));   //"ell"
    console.log(s.slice(-3));    //"ott"
    //s.indexOf("x")   x首次出現的位置,不存在則返回-1
    console.log(s.indexOf("l"));  //2
    console.log(s.indexOf("z"));  //-1
    console.log(s.indexOf("o",6));  //o在位置6之后首次出現的位置,不存在返回-1
    //s.lastIndexOf("x")  x最后出現的位置,不存在則返回-1
    console.log(s.lastIndexOf("o"));  //12
    console.log(s.lastIndexOf("z"));  //-1
    console.log(s.split(","));   //根據“,”將字符串轉換為數組
    console.log(s.replace("o","O"));  //hellOw,pomelott  將第一個“o”替換為“O”
    console.log(s.toUpperCase());  //全文轉換為大寫
    var str1="hellow,";
    var str2="world";
    console.log(str1.concat(str2));  //hellow,world  字符串連接
    //search() 方法用於檢索字符串中指定的子字符串,或檢索與正則表達式相匹配的子字符串。
    console.log(s.search(/pomelo/));  //7  存在則返回首字符下標,不存在則返回-1
    //match() 方法可在字符串內根據正則表達式檢索,若存在則返回檢索后的對象,否則返回null
    console.log(s.match(/pomelo/));  //["pomelo", index: 7, input: "hellow,pomelott"]
    console.log(typeof s.match(/pomelo/));  //object
    console.log(s.match("pop"));  //null

  喜歡請點擊右下角推薦,如有疑問可以留言,轉載請標明出處。


免責聲明!

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



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