前言
字符串作為 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"]
(11)padStart()和padEnd()方法用於補齊字符串的長度。如果某個字符串不夠指定長度,會在頭部或尾部補全
var str = "123" //padStart()和padEnd()方法接收兩個參數,第一個參數是字符串補全生效的最大長度,第二個參數是用來補全的字符串,當補齊的長度小於等於原始長度時不發生裁剪 console.log(str.padStart(5, 'a'));//'aa123' console.log(str.padStart(3, 'a'));//'123' console.log(str.padStart(5));//' 123' console.log(str.padEnd(5, 'a'));//'123aa' console.log(str.padEnd(3, 'a'));//'123' console.log(str.padEnd(5));//'123 '
(12)字符串迭代與解構
//在 for-of 循環中可以通過這個迭代器按序訪問每個字符: for (const c of "abcde") { console.log(c); } // a // b // c // d // e let message = "abcde"; console.log([...message]); // ["a", "b", "c", "d", "e"]
總結
以上就是本文的全部內容,希望給讀者帶來些許的幫助和進步,方便的話點個關注,小白的成長之路會持續更新一些工作中常見的問題和技術點。