js–你需要知道的字元串使用方法(含es6及之後)

前言

  字元串作為 JavScript 的基本數據類型,在開發以及面試過程中作為程式設計師對基礎掌握情況的重要考點,本文來總結一下字元串的相關屬性以及用法。包含了ES6中的一些新語法特性。

正文

  1.字元串的創建

  JavaScript 中創建字元串的方法主要有兩種。一種是通過字面量的方式創建,另一種是通過構造函數創建。分別如下:

    // 字面量方式
    var str = "hello world";
    console.log(str)//hello world
    console.log(typeof str);//string

    // 構造函數方式
    var strr = new String("hello  Serendipity")
    console.log(strr)//String {"hello  Serendipity"}
    console.log(typeof strr);//object

    // 兩種方式區別
    var str = 'hello';
    var strr = new String('hello')
    var strrr = new String('hello')
    console.log(str == strr);//true
    console.log(str === strr);// false 兩者類型不通,分別是String 和 Object 類型
    console.log(strr == strrr);//false  存放在棧中的地址不相同
    console.log(strr === strrr);//false    兩者在堆中存放的值相同,但是 不是指向同一個值,同樣棧中地址不同

 

  2.轉義字元和模板字元串

  字元串中雙引號裡面不能包含雙引號,單引號裡面不能包含單引號,如果想要用到這些關鍵字元,需要使用轉義字元表示,例如:轉義字元  \’可以表示為’              \\表示為\           \\’表示為\’

        var str1 = '001'
        var str2 = '002\'這是\\\\一個字元串·'
        console.log(str1);//001
        console.log(str2);//002'這是\\一個字元串·

  同樣使用轉義字元可以達到換行符、回車的作用:

        //同樣轉義字元實現字元串換行
        var str = '<br>this \
        <br>is a \
        <br>book';
        console.log(str);//<br>this         <br>is a         <br>book
        //轉義字元還可以將有意義的和沒意義的字元進行轉換
        //    \n是新行 \t是回車   \t水平製表符
        var st = 'this\n \ris a \tbook'
        console.log(st);//this
 
                        //is a     book

  es6中為了解決換行導致程式碼不規則的這種問題,引入了模板字元串,用反引號“包裹住字元串達到換行效果,同時可以直接使用類似於插值表達式的方法獲取其值。如下:

        //ES6聲明字元串的模板  反引號~鍵位
        var ss = '<i>www</i>\
        <h2>baidu</h2>.com'
        console.log(ss);//<i>www</i>
                         //<h2>baidu</h2>.com
        //使用反引號聲明字元串 在反引號中不需要使用\換行》》》m模板字元串
        var host = 'www'
        var yuming = 'baidu'
        var qy = 'com';
        var str = `<i>${host}</i><h2>${yuming}</h2>.${qy}`
        console.log(str);//<i>www</i><h2>baidu</h2>.com

 

  3.屬性

  length屬性 ,返回字元串的長度,記住是屬性,不是方法。

  constructor屬性,對創建字元串對象的String構造函數的引用。

  prototype屬性,js中通過構造函數創建的對象實例,都有一個prototype(原型)屬性,這個屬性是一個指針,這個指針指向一個對象,而這個對象就包含了通過構造函數所實例化的所有實例共享的屬性和方法,prototype屬性能讓構造的實例有能力訪問這些屬性和方法。

  4.方法

  (1)charAt()方法,返回指定索引位置的字元。charCodeAt()方法,返回指定索引位置字元對應的unicode值。fromCharCode()方法,將Unicode轉化為字元串。

    var str = "hello Serendipity"
    console.log(str.charAt(2));//l
    console.log(str.charCodeAt(2));//108
    console.log(String.fromCharCode(108));//l

 

  (2)concat()方法,連接兩個字元串,返回連接之後的字元串。

 

    var str1 = "hello "
    var str2 = "serendipity"
    console.log(str1.concat(str2));//hello serendipity    

 

  (3)valueOf()方法,返回某個字元串對象的原始值。toString()方法,返回字元串對象值。

 

    var str = "hello Serendipity"
    console.log(str.valueOf());//hello Serendipity
    console.log(str.toString());//hello Serendipity
    var strr = new String("hello Serendipity")
    console.log(strr.valueOf());//hello Serendipity
    console.log(strr.toString());//hello Serendipity

 

  (4)subString()方法,提取字元串中兩個指定索引之間的字元。substr()方法,從起始索引號提取指定數目的字元。slice()方法提取字元串的片段,並在新的字元串中返回被提取的部分。

 

    var str = "hello Serendippity"
    // substring(from, [to]) 方法用於提取字元串中介於兩個指定下標之間的字元,方返回的子串包括 start 處的字元,
    // 但不包括 stop 處的字元,to 可選,如果省略該參數,那麼返回的子串會一直到字元串的結尾。substring() 不接受負的參數。
    console.log(str.substring(2));//llo Serendippity
    console.log(str.substring(2,5));//llo
    console.log(str.substring(-1));//hello Serendippity

    // substr(start, [length]) 方法可在字元串中抽取從 start 下標開始的指定數目的字元。返回一個新的字元串,包含從 start(包括 start 所指的字元) 處開始的
    //  length 個字元。如果沒有指定 length,那麼返回的字元串包含從 start 到該字元串的結尾的字元。
    console.log(str.substr(2));//llo Serendippity
    console.log(str.substr(2,5));//llo S
    console.log(str.substr(-2));//ty
    
    // slice(start, [end]) 方法可提取字元串的某個部分,返回一個新的字元串。包括字元串從 start 開始(包括 start)到 end 結束(不包括 end)為止的所有字元。
    console.log(str.slice(2));//llo Serendippity
    console.log(str.slice(2,5));//llo
    console.log(str.slice(-2));//ty

 

  (4)indexOf()方法,返回字元串中檢索指定字元串第一次出現的位置。lastIndexOf()方法,返回字元串中檢索指定字元串最後一次出現的位置。includes()方法,判斷字元串中是否包含指定的子字元串。

 

    var str = "hello serendipity"
    console.log(str.indexOf("l"));//2
    console.log(str.lastIndexOf("i"));//14
    console.log(str.includes("dipi"));//true
    console.log(str.includes("pidi"));//false

 

  (5)search()方法,索引與正則表達式相匹配的值。replace()方法,替換與正則表達式匹配的子串。replaceAll()方法,替換與正則表達式匹配的所有子串。match()方法,找打一個或多個正則表達式的匹配。

 

    var str = "hello Serendipity"
    // search()方法接收一個正則作為參數,如果字元串中能匹配正則,則返回匹配字串的起始位置,否則返回-1
    console.log(str.search(/llo/));//2
    console.log(str.search(/LLO/));//-1
    //replace()接收兩個參數,第一個為需要替換的正則或者字元串,第二個參數為替換成為的內容,返回替換之後的結果
    console.log(str.replace(/l/,"o"));//heolo Serendipity
    // replaceAll()接收兩個參數,第一個為需要替換的正則或者字元串,第二個參數為替換成為的內容,返回替換之後的結果,
   //相比replace,只是多了全局的作用範圍,同樣在replace中用正則可以實現replaceAll的效果
console.log(str.replace(/l/g,"o"));//heooo Serendipity console.log(str.replaceAll("l","o"));//heooo Serendipity

 

  (6)toUpperCase()方法,把字元串轉為大寫。toLowerCasse()方法,把字元串轉為小寫。toLocalLowerCase()方法和toLocalUpperCase()方法根據主機語言環境把字元串轉化為相應的大小寫。

 

    var str = "hello Serendipity"
    console.log(str.toUpperCase());//HELLO SERENDIPITY
    console.log(str.toLowerCase());//hello Serendipty
    console.log(str.toLocaleUpperCase());//HELLO SERENDIPITY
    console.log(str.toLocaleLowerCase());//hello Serendipty

 

  (7)trim()方法,去掉字元串兩頭的空格。

 

    var str = "   hello Serendipity   "
    console.log(str.trim());//hello Serendipty
    console.log(str.length);//23
    console.log(str.trim().length);//17

 

  (8)startsWith()方法,判斷字元串是否以指定的字元串開始的。endsWith()方法,判斷字元串是否是以指定的字元串結束的。

 

    var str = "hello Serendipity"
    console.log(str.startsWith("hello"));//true
    console.log(str.startsWith("seren"));//false
    console.log(str.endsWith("pity"));//true
    console.log(str.endsWith("hrllo"));//false

 

  (9)repeat()方法,返回一個字元串複製粘貼多次之後的新字元串。

 

    var str = "hello Serendipity"
    console.log(str.repeat(2));//hello Serendipityhello Serendipity

  (10)split()方法,將字元串按指定字元分割為數組

    var str = "red,blue,green"
    console.log(str.split(","));//(3) ["red", "blue", "green"]

總結

  以上就是本文的全部內容,希望給讀者帶來些許的幫助和進步,方便的話點個關注,小白的成長踩坑之路會持續更新一些工作中常見的問題和技術點。