JavaScript?引用類型之原始值包裝類型String
String 原始值包裝類型
String是對應(yīng)字符串的引用類型。要?jiǎng)?chuàng)建一個(gè)String 對象,使用String 構(gòu)造函數(shù)并傳入一個(gè)數(shù)值。
let stringObject = new String("hello world");String 對象的方法可以在所有字符串原始值上調(diào)用。3個(gè)繼承的方法valueOf,toLocalString()和String()都返回對象的原始字符串值。 每個(gè)String對象都有一個(gè)length屬性,表示字符串中字符的數(shù)量。
let stringValue = "hello world"; console.log(stringValue.length);// "11"
String 類型提供了很多方法來解析和操作字符串。比如字符串截取函數(shù),slice(),substr(),substring(),字符串連接函數(shù)concat(),查詢字符串位置相關(guān)函數(shù), indexOf(),lastIndexOf(),字符串大小寫轉(zhuǎn)換函數(shù)toLowerCase(),toLocalLowerCase(),toUpperCase(),toLocalUpperCase()等等,本文將對幾乎所有的字符串方法進(jìn)行總結(jié)梳理,以便后用。
String 原始值包裝類型 操作方法
1.字符串編碼常規(guī)化函數(shù) normalize()方法
某些Unicode 字符可以有很多種編碼方式。有的字符可以通過一個(gè)BMP字符表示,也可以通過一個(gè)代理對表示。
//U+00C5 上面帶圓圈的大寫拉丁字母A console.log(String.fromCharCode(0x00C5)); //? //U+212B:長度單位 “?!? console.log(String.fromCharCode(0x212B));// ? //U+004 大寫拉丁字母A //U+030A: 上面加個(gè)圓圈 console.log(String.fromCharCode(0x0041,0x030A)); // ?
比較操作符不在于字符開起來是什么樣的,因此著三個(gè)字符互不相等。
let a1 = String.fromCharCode(0x00C5), a2 = String.fromCharCode(0x212B), a3 = String.fromCharCode(0x0041,0x030A); console.log(a1,a2,a3); // ?,?,? console.log(a1 === a2);//false console.log(a2 === a3);//false console.log(a1 === a3);//false
為解決這個(gè)問題,Unicode 提供了4種規(guī)范化形式, 可以將上面的字符規(guī)范化為一致的格式,無論底層字符的代碼是什么。這4種規(guī)范化形式是:NFD,NFC,NFKD和NFKC??梢允褂胣ormalize()方法對字符串應(yīng)用上述規(guī)范化形式,使用時(shí)需要穿入表示哪種形式的字符串:"NFD","NFC","NFKD","NFKC";
通過比較字符串與其調(diào)用normalize()的返回值,就可以知道該字符串是否已經(jīng)規(guī)范化了:
let a1 = String.fromCharCode(0x00C5),
a2 = String.fromCharCode(0x212B),
a3 = String.fromCharCode(0x0041,0x030A);
// U+00C5 是對0+212B 進(jìn)行NFC/NFKC 規(guī)范化之后的結(jié)果
console.log(a1 === a1.normalize("NFD")); // false
console.log(a1 === a1.normalize("NFC"));//true
console.log(a1 === a1.normalize("NFKD"));// false
console.log(a1 === a1.normalize("NFKC"));//true
//U+212B 是未規(guī)范化的
console.log(a2 === a2.normalize("NFD")); // false
console.log(a2 === a2.normalize("NFC"));//false
console.log(a2 === a2.normalize("NFKD"));// false
console.log(a2 === a2.normalize("NFKC"));//false
//U+0041/U+030A 是對0+212B 進(jìn)行NFD/NFKD 規(guī)范化之后的結(jié)果
console.log(a3 === a3.normalize("NFD")); // true
console.log(a3 === a3.normalize("NFC"));//false
console.log(a3 === a3.normalize("NFKD"));// true
console.log(a3 === a3.normalize("NFKC"));//false選擇同一種規(guī)范化形式可以讓比較操作符返回正確的結(jié)果:
let a1 = String.fromCharCode(0x00C5),
a2 = String.fromCharCode(0x212B),
a3 = String.fromCharCode(0x0041,0x030A);
console.log(a1.normalize("NFD") === a1.normalize("NFD")); // false
console.log(a2.normalize("NFKC") === a2.normalize("NFKC"));//false
console.log(a3.normalize("NFC") === a3.normalize("NFC"));// false2.字符串拼接函數(shù)concat()
concat()用于將一個(gè)或多個(gè)字符串拼接成一個(gè)新字符串。
let stringValue = "hello";
let result = stringValue.concat("world");
console.log(result);// hello world
console.log(stringValue);// hello stringValue 調(diào)用concat()方法返回的結(jié)果是得到"hello world" ,但stringValue 的值保持不變。
concat()方法可以接受任意多個(gè)參數(shù),因此可以一次性拼接多個(gè)字符串
let stringValue = "hello ";
let result = stringValue.concat("world","!");
console.log(result);// "hello world!"
console.log(stringValue); // "hello "3.字符串提取子字符串方法:slice(),substr(),substring()
slice(),substr(),substring() 這三個(gè)方法都返回它們的字符串的一個(gè)子字符串,而且都接收一個(gè)或兩個(gè)參數(shù)。
第一個(gè)參數(shù)表示子字符串開始的位置,第二個(gè)參數(shù)表示子字符串結(jié)束的位置。
對slice()和substring()而言,第二個(gè)參數(shù)是提取結(jié)束的位置(即該位置之前的字符會被提取出來)。
對substr()而言,第二個(gè)參數(shù)表示返回的子字符串的字符數(shù)量。
任何位情況下,省略第二個(gè)參數(shù)都意味著提取到字符串末尾。
與concat()方法一樣,slice(),substr()和substring()也不會修改調(diào)用它們的字符串。
let stringValue = "hello world"; // 傳遞一個(gè)參數(shù),相當(dāng)于提取到字符串末尾 console.log(stringValue.slice(3)); //"lo world" console.log(stringValue.substr(3)); //"lo world" console.log(stringValue.substring(3); //"lo world" // 傳遞2個(gè)參數(shù),slice(),substring()結(jié)果一致,substr() 結(jié)果與前兩者有區(qū)別 console.log(stringValue.slice(3,7)); //"lo w" console.log(stringValue.substr(3,7)); //"lo w" console.log(stringValue.substring(3,7); //"lo worl"
當(dāng)傳遞給slice(),substring(),substr的參數(shù)為負(fù)數(shù)時(shí),這三個(gè)函數(shù)的行為有所不同。 slice()方法將所有負(fù)數(shù)參數(shù)都當(dāng)成字符串長度加上參數(shù)值。
substring()方法將所有負(fù)參數(shù)值都轉(zhuǎn)換為0.
substr()方法將第一個(gè)負(fù)參數(shù)值當(dāng)成字符串長度加上該值,將第二個(gè)負(fù)參數(shù)值轉(zhuǎn)換為0.
let stringValue = "hello world"; console.log(stringValue.slice(-3));// "rld" console.log(stringValue.substring(-3));//"hello world" console.log(stringValue.subst(-3));//"rld" console.log(stringValue.slice(3,-4));// "lo w" 轉(zhuǎn)化為 (3,-4 + 11) = (3,7) console.log(stringValue.substring(3,-4));//"hel",轉(zhuǎn)化為(3,0),這個(gè)函數(shù)會將較小的參數(shù)作為起點(diǎn),較大的參數(shù)作為終點(diǎn),所以相當(dāng)于(0,3) console.log(stringValue.substr(3,-4));//"" 轉(zhuǎn)化為(3,0)
4.字符串位置方法 indexOf(),lastIndexOf()
有兩個(gè)方法用于在字符串中定位子字符串,indexOf()和lastIndexOf().這兩個(gè)方法在字符串中搜索傳入的字符串,并返回位置(如果沒找到,則返回-1.).
兩者的區(qū)別在于,indexOf()從字符串開頭開始查找子子字符串,而lastIndexOf()方法從公字符串末尾開始查找子字符串。
let stringValue = "hello world";
console.log(stringValue.indexOf("o");//4
console.log(stringValue.lastIndexOf("o"));// 7 這兩個(gè)方法都可以接收第二個(gè)參數(shù),表示開始搜索的位置。這意味著,indexOf()會從這個(gè)參數(shù)指定的位置開始向字符串末尾搜索,忽略位置之前的字符;lastIndexOf()則會從這個(gè)參數(shù)指定的位置開始向字符串開頭開始搜索,忽略該位置之后直到字符串末尾的字符。
需要注意的是,返回值的位置永遠(yuǎn)是搜索的子字符串在搜索字符串中的正序位置,不會因?yàn)榈诙€(gè)參數(shù)而改變。并且傳入的搜索的范圍包含第二個(gè)參數(shù)傳遞的位置。
let stringValue = "hello world";
console.log(stringValue.indexOf("o",7));// 7
console.log(stringValue.lastIndexOf("o",7));//75.字符串包含方法:startsWith(),endsWith()和includes()
ECMAScript 6 增加了3個(gè)用于判斷字符串是否包含另一個(gè)字符串的方法:startsWith(),endsWith()和includes().這些方法都會從字符串中搜素傳入的字符串,并返回一個(gè)是否包含的布爾值。
區(qū)別在于,startsWith()檢查開始于索引0的匹配項(xiàng),endsWith()檢查開始于索引(string.length - substring.length())的匹配項(xiàng),而includes()檢查整個(gè)字符串。
let message = "foobarbaz";
console.log(message.startsWith("foo"));//true
console.log(message.endsWith("bar"));//false
console.log(message.endsWith("baz"));//true
console.log(message.startsWith("bar"));//false
console.log(message.includes("foo"));//true
console.log(message.includes("qux"));//falsestartsWith()和incluedes()方法接收可選的第二個(gè)參數(shù),表示開始搜索的位置。如果傳入第二個(gè)參數(shù),則意味著這兩個(gè)方法會從指定位置向著字符串末尾搜索,忽略位置之前的所有字符。
let message = "foobarbaz";
console.log(message.startsWith("foo"));//true
console.log(message.startsWith("foo",1));//false
console.log(message.includes("bar"));//true
console.log(message.includes("bar",4));//falseendsWith()方法接收可選的第二個(gè)參數(shù),表示把傳入的第二個(gè)參數(shù)作為字符串結(jié)尾的位置。如果不提供這個(gè)參數(shù),那么默認(rèn)就是字符串長度。如果提供了這個(gè)參數(shù),那么就好像字符串直郵那么差多字符一樣。
let message = "foobarbaz";
console.log(message.endsWith("bar"));//false
console.log(message.endsWith("bar",6));//true6.去除字符串前后空格的方法 trim(),trimLeft(),trimRight()
ECMAScript 在所有字符串上提供了trim()方法。這個(gè)方法會創(chuàng)建字符串的一個(gè)副本,刪除前后的所有空格,在返回結(jié)果。 trimLeft()和trimRight()方法分別從字符串開始和末尾清理空格符。
let stringValue = " hello world "; let trimmedStringValue = stringValue.trim(); console.log(stringValue); // " hello world " console.log(trimmedStringValue);//"hello world" console.log(stringValue.trimLeft());//"hello world " console.log(stringValue,trimRight());//" hello world"
7.字符串的重復(fù)復(fù)制 repeat()
ECMAScript 在所有字符串上都提供了repeat()方法。這個(gè)方法接收一個(gè)整數(shù)參數(shù),表示要將字符串復(fù)制多少次,然后返回拼接所有副本后的結(jié)果。
let stringValue = "na "; console.log(stringValue.repeat(3) + "batman"); // na na na batman
8.字符串填充函數(shù) padStart() 和 padEnd()方法
padStart() 方法和padEnd()方法會復(fù)制字符串,如果小于指定長度,則在相應(yīng)一邊填充字符,直至滿足長度條件。這兩個(gè)方法的第一個(gè)參數(shù)是長度,第二個(gè)參數(shù)是可選的填充字符串,默認(rèn)為空字符串(U+0020).
let stringValue = "foo"; console.log(stringValue.padStart(6)); // " foo" console.log(stringValue.padStart(9,"."));// "......foo" console.log(stringValue.padEnd(6));//"foo "; console.log(stringValue.padEnd(9,"."));//"foo......"
可選的第二個(gè)參數(shù)并不局限于一個(gè)字符。如果提供了多個(gè)字符的字符串,則會將其拼接并截?cái)嘁云ヅ渲付ㄩL度。此外,如果長度小于或等于字符串長度,則會返回原始字符串。
傳入的第二個(gè)參數(shù)表示的是字符串的總長度
let stringValue = "foo"; console.log(stringValue.padStart(8,"bar"));//"barbafoo" console.log(stringValue.padEnd(8,"bar"));//"foobarba" console.log(stringValue.padEnd(2));// "foo"
9.字符串迭代與 解構(gòu)
字符串的原型上暴露了一個(gè)@@iterator 方法,表示可以迭代字符串的每個(gè)字符。 可以手動調(diào)用迭代器
let message = "abc";
let stringIterator = message[Symbol.iteator]();
console.log(stringIterator.next());// {value:"a",done:false}
console.log(stringIterator.next());//{value:"b",done:false}
console.log(stringIterator.next());//{value:"c",done:false}
console.log(stringIterator.next());//{value:undefiend,done:true}在for 循環(huán)中可以通過這個(gè)迭代器按序訪問每個(gè)字符:
for (const c of "abc") {
console.log(c);
}
// a
//b
//c有了這個(gè)迭代器之后,字符串就可以通過結(jié)構(gòu)操作符來解構(gòu)了。比如,可以方便的把字符串分割為數(shù)組:
let message = "abcde"; console.log([...message]);// ["a","b","c","d","e"]
10.字符串大小寫轉(zhuǎn)換
字符串大小寫轉(zhuǎn)換函數(shù)涉及4個(gè)方法:toLowerCase(),toLocaleLowerCase(),toUpper()和toLocale UpperCase().toLowerCase()和toUpperCase()方法是原來就有的 方法,與java.lang.String 中的方法同名。toLocaleLowerCase()和toLocaleUpperCase()方法旨在基于特定地區(qū)實(shí)現(xiàn)。在很多地區(qū),地區(qū)的方法與通用的方法是一樣的。但在少數(shù)語言中(如土耳其語),Unicode大小寫轉(zhuǎn)換需應(yīng)用特殊規(guī)則,要使用地區(qū)特定的方法才能實(shí)現(xiàn)轉(zhuǎn)換。
let stringValue = "hello world"; console.log(stringValue.toUpperCase());//"HELLO WORLD" console.log(stringValue.toLocaleUpperCase());//"HELLO WORLD" console.log(stringValue.toLocaleLowerCase());//"hello world" console.log(stringValue.toLowerCase());// "hello world"
11.字符串模式匹配方法 match(),search(),replace(),split()
match()
String 類型專門為字符串中實(shí)現(xiàn)模式匹配設(shè)計(jì)了幾個(gè)方法。第一個(gè)就是match()方法,這個(gè)方法本質(zhì)上跟RegExp對象的exec()方法相同。match()方法接收一個(gè)參數(shù),可以是一個(gè)正則表達(dá)式字符串,也可以是一個(gè)RegExp對象
let text = "cat, bat, sat, fat"; let pattern = /.at/; //等價(jià)于pattern.exec(text) let matches = text.match(pattern); console.log(matches.index);//0 console.log(matches[0]);// "cat" console.log(pattern.lastIndex);// 0
search()
另一個(gè)查找模式的字符串方法是search().這個(gè)方法唯一的參數(shù)與match()方法一樣:正則表達(dá)式或RegExp對象。這個(gè)方法返回模式第一個(gè)匹配的位置索引,如果沒有找到返回-1.search()始終從字符串開頭向后向后匹配模式。
let text = "cat, bat, sat, fat"; let pos = text.search(/at/); console.log(pos);//1
replace()
為簡化字符串替換操作,ECMAScript提供了replace()方法。
這個(gè)方法接收兩個(gè)參數(shù),第一個(gè)參數(shù)可以是一個(gè)RegExp對象或一個(gè)字符串(這個(gè)字符串不會轉(zhuǎn)化為正則表達(dá)式),第二個(gè)參可以是一個(gè)字符串或函數(shù)。
如果第一個(gè)參數(shù)是字符串,那么只會替換第一個(gè)字符串,要想替換所有子字符串,第一個(gè)參數(shù)必須為正則表達(dá)式并且?guī)謽?biāo)記。
let text = "cat, bat, sat, fat";
let result = text.replace("at","ond");
console.log(result);// "cond, bat, sat, fat"
result = text.replace(/at/g,"ond);
console.log(result);//"cond, bond, sond, fond"第二個(gè)參數(shù)是字符串的情況下,有幾個(gè)特殊的字符序列,可以用來插入正則表達(dá)操作的值。 ECMAScript262 規(guī)定了如下的值。
| 字符序列 | 替換文本 |
|---|---|
| $$ | $ |
| $& | 匹配整個(gè)模式的子字符串。與RegExp.lastMatch相同 |
| $' | 匹配的子字符串之前的字符串。與RegExp.rightContext 相同 |
| $` | 匹配的子字符串之后的字符串。與RegExp.leftContext 相同 |
| $n | 匹配第n個(gè)捕獲組的字符串,其中n 是 0~9.比如,1 是匹配的第一個(gè)捕獲組的字符串,1是匹配的第一個(gè)捕獲組的字符串,2 是匹配的第二個(gè)捕獲組的字符串,以此類推。如果沒有捕獲組,則值為空字符串 |
| $nn | 匹配第nn個(gè)捕獲組字符串,其中nn 是01~99.比如,01 是匹配第一個(gè)捕獲組的字符串,01是匹配第一個(gè)捕獲組的字符串,02 是匹配第二個(gè)捕獲組的字符串,以此類推。如果沒有捕獲組,則值為空字符串 |
使用這些特殊的序列,可以在替換文中使用之前匹配的內(nèi)容
let text = "cat, bat, sat, fat"; result = text.replace(/(.at)/g,"word ($1)"); console.log(result); // word(cat), word(bat), word(sat), word(fat)
replace() 第二個(gè)參數(shù)可以是一個(gè)函數(shù)。在 在只有一個(gè)匹配項(xiàng)時(shí),這個(gè)函數(shù)會收到3個(gè)參數(shù):與整個(gè)模式匹配的字符串,匹配項(xiàng)在字符串中的開始位置,以及整個(gè)字符串。在有多個(gè)捕獲組的情況下,每個(gè)匹配捕獲組的字符串也會作為參數(shù)傳遞這個(gè)函數(shù),但最后兩個(gè)參數(shù)還是與整個(gè)模式匹配的開始位置和原始字符串。這個(gè)函數(shù)應(yīng)該返回一個(gè)字符串,表示應(yīng)該把撇皮項(xiàng)替換成什么。使用函數(shù)作為第二個(gè)參數(shù)可以更細(xì)致的控制替換過程。
function htmlEscape(text) {
return text.replace(/[<>"&]/g,function(match,pos,originalText){
switch(match) {
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "\"":
return """;
}
});
}
console.log(htmlEscape("<p class=\"greeting\">Hello world!<p>"));//<p class="greeting">Hello world!<p>split()
最后一個(gè)與模式匹配相關(guān)的字符串方法是split().這個(gè)方法會根據(jù)傳入的分隔符將字符串拆分成數(shù)組。作為分隔符的參數(shù)可以是字符串,也可以是RegExp對象。(字符串分隔符不會被這個(gè)方法當(dāng)成增則表達(dá)式。)還可以傳入第二個(gè)參數(shù),即數(shù)組大小,確保返回的數(shù)組不會超過指定大小。
let colorText = "red,blue,green,yellow";
let color1 = colorText.split(",");// ["red","blue","green","yellow"]
let color2 = colorText.split(",",2);//["red","blue"];
let colors = colorText.split(/[^,]/);// ["",",",",",",",""]12.localeCompare()
localCompare()方法比較兩個(gè)字符串,返回如下3個(gè)值中的一個(gè):
- 如果按照字母表順序,字符串應(yīng)該排在字符串參數(shù)牽頭,則返回負(fù)值。(通常是-1,具體還要看實(shí)際值相關(guān)的實(shí)現(xiàn)。)
- 如果字符串與字符串參數(shù)相等,則返回0
- 如果按照字母表順序,字符串應(yīng)該排在字符串參數(shù)后頭,則返回正值。(通常是1,具體還要看與實(shí)際值相關(guān)的實(shí)現(xiàn))
let stringValue = "yellow";
console.log(stringValue.localeCompare("brick");//1
console.log(stringValue.localeCompare("yellow");// 0
console.log(stringValue.localeCompare("zoo");//-1因?yàn)榉祷氐木唧w值可能因?yàn)榫唧w實(shí)現(xiàn)而異,所以最好像下面方式一樣使用localeCompare()
function detemineOrder(value){
let result = stringValue.localeCompare(value);
if(result < 0 ){
console.log(`The string 'yellow' comes before the string '${value}'.`);
}else if( result > 0) {
console.log(`The string 'yellow' comes after the string '${value}'.`);
}else {
console.log(`The string 'yellow' comes equal the string '${value}'.`);
}
}
detemineOrder("brick");
detemineOrder("yellow);
detemineOrder("zoo);到此這篇關(guān)于JavaScript 引用類型之原始值包裝類型String的文章就介紹到這了,更多相關(guān)JS 裝類型String內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS解決Date對象在IOS中的“大坑” 以及時(shí)間格式兼容問題
這篇文章主要介紹了JS解決Date對象在IOS中的“大坑” 以及時(shí)間格式兼容問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
如何用JS實(shí)現(xiàn)網(wǎng)頁瀑布流布局
這篇文章主要介紹了如何用JS實(shí)現(xiàn)網(wǎng)頁瀑布流布局,幫助大家更好的利用JavaScript制作網(wǎng)頁,感興趣的朋友可以了解下2021-04-04
詳解JavaScript前端如何實(shí)現(xiàn)截屏功能
這篇文章主要為大家詳細(xì)介紹了JavaScript前端如何實(shí)現(xiàn)截屏功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04

