JavaScript中字符串相關(guān)的方法使用總結(jié)
JavaScript中的字符串是由16位碼元code unit組成。通常來說,一個字符=16位碼元,該類字符也叫做單碼元字符。還有一種字符組成策略是代理對,它由兩對16位碼元組成,即一個字符對應(yīng)兩個16位碼元,用于增補字符。
JavaScript使用兩種Unicode編碼混合的策略:USC-2和UTF-16。
深入了解字符編碼
- The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
- JavaScript’s Internal Character Encoding:UCS-2 or UTF-16?
字符串原始值可以調(diào)用所有String對象的方法;有3個繼承的方法:valueOf()、toLocaleString()、toString(),它們都返回字符串對象的原始字符串值;有1個length屬性,其值為字符串所包含的字符數(shù)量。
下面介紹JavaScript字符串的相關(guān)方法。
不做說明的都不改變原字符串。
1.charAt、charCodeAt、codePointAt
charAt獲取指定位置字符。charCodeAt獲取指定位置字符的編碼(16進制變成10進制)。
const str="Hello,世界!"; console.log(str.charAt(0)); //H console.log(str.charAt(7)); //界 console.log(str.charCodeAt(0)); //72 console.log(str.charCodeAt(7)); //30028 console.log(parseInt(30028).toString(16)); //754c
charCodeAt只適合單碼元字符,而代理對字符需要使用codePointAt。
為了正確解析既包含單碼元字符又包含代理對字符的字符串,使用codePointAt接收16位碼元的索引并返回該索引位置上的碼點(Unicode中一個字符的完整標識)。
const str = "ab??ba"; console.log(str.charCodeAt(2)); // 55357 console.log(str.codePointAt(2)); // 128514
2.fromCharCode、fromCodePoint
fromCharCode用于根據(jù)給定的UTF-16碼元創(chuàng)建字符,可以接受多個數(shù)值,生成一個字符串。fromCodePoint用給定碼點創(chuàng)建字符,同樣可接受多個值生成一個字符串。
// 使用 fromCharCode() 創(chuàng)建字符 const char1 = String.fromCharCode(65); // 65 是字符 'A' 的UTF-16碼元 console.log(char1); // 輸出:A // 使用 fromCodePoint() 創(chuàng)建字符 const char2 = String.fromCodePoint(128514); // 128514 是笑臉符號的碼點 console.log(char2); // 輸出:??
兩個一樣的字符一定相等嗎?如果這兩個字符看著一樣,但是對應(yīng)的字符編碼不一樣,那么便不相等,例如
const char1 = 'A'; // 拉丁字母大寫A const char2 = 'Α'; // 希臘字母大寫Alpha // 比較兩個字符是否相等 console.log(char1 === char2); // 輸出:false,盡管外觀相似,但字符編碼不同 // 獲取字符編碼 console.log(char1.charCodeAt(0)); // 輸出:65,字符A的Unicode編碼 console.log(char2.charCodeAt(0)); // 輸出:913,字符Α的Unicode編碼
3.concat
concat用于拼接字符串,可以一次性拼接多個字符串,當然我們更常使用 + 號來拼接字符串。
let str="Hello " console.log(str.concat("World","!")) //"Hello World!" console.log(str) //"Hello"
4.slice、substring、substr
這三個方法有一定相似,但也有重大不同,且看下文。
它們都用于提取子字符串,都接受1或2個參數(shù),且第一個參數(shù)都是起始位置的索引,如果省略第二個參數(shù),表示截取到字符串末尾。不同的地方是,slice和substring第二個參數(shù)是結(jié)束位置的索引(截取部分不包括該結(jié)束位置),而substr第二個參數(shù)是從起始位置截取字符串的字符個數(shù)。值得注意的是,substring它會將較小的數(shù)字當成起始位置,可能會出現(xiàn)第一參數(shù)大于第二參數(shù)的情況。
對于負數(shù)參數(shù),slice會將它們都加上字符串長度(即從右往左數(shù)),直到為正數(shù);substr會將第一個負參加上字符串長度,將第二個負參變?yōu)?;substring將所有負參轉(zhuǎn)為0。
let str = "Hello world!" console.log(str.slice(0)) //Hello world! console.log(str.slice(0, 5)) //Hello console.log(str.substring(0)) //Hello world! console.log(str.substring(0, 5)) //Hello console.log(str.substr(0)) //Hello world! console.log(str.substr(0, 5)) //Hello console.log(str.slice(-5)) //orld! console.log(str.substring(-5)) //Hello world! console.log(str.substr(-5)) //orld! console.log(str.slice(0, -5)) //Hello w console.log(str.substring(0, -5)) //空字符串 console.log(str.substr(0, -5)) //空字符串 console.log(str.slice(-5, -2)) //orl console.log(str.substring(-5, -2)) //空字符串 console.log(str.substr(-5, -2)) //空字符串 console.log(str.slice(-2, -5)) //空字符串 console.log(str.substring(-2, -5)) //空字符串 console.log(str.substr(-2, -5)) //空字符串 console.log(str.slice(5, 0)) //空字符串 console.log(str.substring(5, 0)) //Hello console.log(str.substr(5, 0)) //空字符串
5.indexOf和lastIndexOf
前文已經(jīng)介紹了根據(jù)位置獲取字符串的方法,我們也可以根據(jù)字符串獲取它的位置——indexOf和lastIndexOf,它們區(qū)別在于indexOf是從前往后找,而lastIndexOf是從后往前找。如果沒有找到,則返回-1。這兩個方法可以接受第二參數(shù),表示開始搜索位置。
6.startsWith、endsWith、includes
startsWith、endsWith、includes都是判斷是否包含某字符串的方法,返回布爾值。
includes檢查整個字符串。
startsWith和endsWith分別是匹配開頭和結(jié)尾是否有傳入字符串。
startsWith和includes都接受第二個參數(shù),表示起始搜索位置。
7.trim、trimLeft、trimRight
trim方法刪除字符串前后所有空格。trimLeft、trimRight分別刪除字符串左邊空格和字符串右邊空格。
8.repeat
repeat方法接受一個整數(shù)作為參數(shù),表示字符串復制的次數(shù),然后返回它們拼接起來的字符串。
9.padStart、padEnd
pad——填充。
padStart和padEnd分別在字符串前面和字符串后面填充指定長度的指定字符串。第一參數(shù)是填充后字符串要達到的長度,第二參數(shù)是要填充的字符串。
let str = "Hello" console.log(str.padStart(10, "World")) //WorldHello console.log(str.padEnd(10, "World")) //HelloWorld
10.toLowerCase、toLocaleLowerCase、toUpperCase、toLocaleUpperCase
toLowerCase用于將字符串中的所有字符轉(zhuǎn)換為小寫,它不受地域設(shè)置的影響,只是簡單地將字符轉(zhuǎn)換為小寫形式。toLocaleLowerCase()不同之處在于,它會受到地域設(shè)置的影響,可能會根據(jù)當前區(qū)域設(shè)置將某些特定字符轉(zhuǎn)換為小寫形式。
toUpperCase、toLocaleUpperCase同上。
11.模式匹配相關(guān)方法
第一個是match,它本質(zhì)上和RegExp的exec方法相同,返回匹配結(jié)果的數(shù)組形式。如果使用全局模式g,它會返回所有匹配結(jié)果的數(shù)組,否則返回一個數(shù)組,其中第一個元素是匹配到的字符串,后續(xù)元素是正則表達式中的捕獲組。
let str = "To be what we are, and to become what we are capable of becoming, is the only end of life." // 使用match匹配所有包含a的單詞 let reg1 = /\b[a-zA-Z]*a[a-zA-Z]*\b/g console.log(str.match(reg1)) // [ 'what', 'are', 'and', 'what', 'are', 'capable' ] // 使用match匹配包含a的單詞,不使用全局匹配 let reg2 = /\b[a-zA-Z]*a[a-zA-Z]*\b/ console.log(str.match(reg2)) // [ // 'what', // index: 6, // input: 'To be what we are, and to become what we are capable of becoming, is the only end of life.', // groups: undefined // ]
第二個是search,返回匹配到的索引位置,沒有匹配項就返回-1。
let str = "To be what we are, and to become what we are capable of becoming, is the only end of life." // 使用search匹配we let reg = /we/g console.log(str.search(reg)) // 11
第三個是replace,它使用新的字符串或函數(shù)替換正則表達式匹配的內(nèi)容。
const originalString = "Hello, world! Hello, universe!"; // 替換字符串中的單個匹配項 const replacedString1 = originalString.replace("world", "friends"); console.log(replacedString1); // 輸出:Hello, friends! Hello, universe! // 使用正則表達式進行替換(只替換第一個匹配項) const replacedString2 = originalString.replace(/Hello/, "Hi"); console.log(replacedString2); // 輸出:Hi, world! Hello, universe! // 使用正則表達式進行替換(替換所有匹配項) const replacedString3 = originalString.replace(/Hello/g, "Hi"); console.log(replacedString3); // 輸出:Hi, world! Hi, universe! // 使用$1、$2、$3、$4等來替換匹配項 const replacedString4 = originalString.replace(/(Hello), (world)! (Hello), (universe)!/g, "$3, $4! $1, $2!"); console.log(replacedString4); // 輸出:Hello, universe! Hello, world! // 使用函數(shù)來替換匹配項 const replacedString5 = originalString.replace(/(Hello), (world)! (Hello), (universe)!/g, function (matched, p1, p2, p3, p4, offset, original) { console.log(matched) // 匹配到的字符串 console.log(offset) // 匹配到的字符串在原字符串中的偏移量 console.log(original) // 原字符串 return p3 + ", " + p4 + "! " + p1 + ", " + p2 + "!"; } ); console.log(replacedString5); // 輸出:Hello, universe! Hello, world!
最后一個是split,它根據(jù)傳入的分隔符將字符串劃分為一個數(shù)組,分隔符可以是字符串或RegExp對象。
const str="apple,banana,orange" //以逗號作為分隔符 console.log(str.split(",")) //["apple","banana","orange"] //限定數(shù)組大小 console.log(str.split(",",2)) //["apple","banana"] //使用正則表達式 const text="apple orange\tbanana" const parts=text.split(/\s+/) //匹配連續(xù)空格 console.log(parts) //["apple","orange","banana"]
12.迭代方法
字符串的原型上暴露了@@iterator方法
const str = "abc" const str2 = str[Symbol.iterator]() console.log(str2.next()) //{ value: 'a', done: false } console.log(str2.next()) //{ value: 'b', done: false } console.log(str2.next()) //{ value: 'c', done: false } console.log(str2.next()) //{ value: undefined, done: true }
通過該迭代器,我們使用for-of遍歷字符串,以及使用解構(gòu)操作符結(jié)構(gòu)字符串。
13.localeCompare
localeCompare比較字符串與字符串參數(shù)在字母表的順序前后,如果字符串位于字符串參數(shù)前,則返回負值;如果相等,則返回0;如果字符串位于字符串參數(shù)后,則返回正值。
到此這篇關(guān)于JavaScript中字符串相關(guān)的方法使用總結(jié)的文章就介紹到這了,更多相關(guān)JavaScript字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
5個你不知道的JavaScript字符串處理庫(小結(jié))
這篇文章主要介紹了5個你不知道的JavaScript字符串處理庫,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06