梳理總結(jié)JavaScript的23個(gè)String方法
簡單介紹
JavaScript 中的String類型用于表示文本型的數(shù)據(jù)。它是由無符號整數(shù)值(16bit)作為元素而組成的集合。字符串中的每個(gè)元素在字符串中占據(jù)一個(gè)位置. 第一個(gè)元素的 index 值是 0,下一個(gè)元素的 index 值是 1,以此類推。字符串的長度就是字符串中所含的元素個(gè)數(shù).你可以通過 String 字面值或者 String 對象兩種方式創(chuàng)建一個(gè)字符串。
1、charAt()
字符串中的字符從左向右索引,第一個(gè)字符的索引值為 0,最后一個(gè)字符(假設(shè)該字符位于字符串 stringName 中)的索引值為
stringName.length - 1
。 如果指定的 index 值超出了該范圍,則返回一個(gè)空字符串
var anyString = "Brave new world"; console.log("The character at index 0 is '" + anyString.charAt(0) + "'"); console.log("The character at index 1 is '" + anyString.charAt(1) + "'"); console.log("The character at index 2 is '" + anyString.charAt(2) + "'"); console.log("The character at index 3 is '" + anyString.charAt(3) + "'"); console.log("The character at index 4 is '" + anyString.charAt(4) + "'"); console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
輸出:
The character at index 0 is 'B'
The character at index 1 is 'r'
The character at index 2 is 'a'
The character at index 3 is 'v'
The character at index 4 is 'e'
The character at index 999 is ''
2、charCodeAt()
返回
0
到65535
之間的整數(shù),表示給定索引處的 UTF-16 代碼單元
"ABC".charCodeAt(0) // returns 65:"A" "ABC".charCodeAt(1) // returns 66:"B" "ABC".charCodeAt(2) // returns 67:"C" "ABC".charCodeAt(3) // returns NaN
3、codePointAt()
如果在指定的位置沒有元素則返回
undefined
。如果在索引處開始沒有 UTF-16 代理對,將直接返回在那個(gè)索引處的編碼單元。
'ABC'.codePointAt(1); // 66 '\uD800\uDC00'.codePointAt(0); // 65536 'XYZ'.codePointAt(42); // undefined
4、indexOf()
返回調(diào)用它的
String
對象中第一次出現(xiàn)的指定值的索引,從fromIndex
處進(jìn)行搜索。如果未找到該值,則返回 -1
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'; const searchTerm = 'dog'; const indexOfFirst = paragraph.indexOf(searchTerm); console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`); // expected output: "The index of the first "dog" from the beginning is 40" console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`); // expected output: "The index of the 2nd "dog" is 52"
5、lastIndexOf()
返回調(diào)用
String
對象的指定值最后一次出現(xiàn)的索引,在一個(gè)字符串中的指定位置 fromIndex處從后向前搜索。如果沒找到這個(gè)特定值則返回-1
'canal'.lastIndexOf('a'); // returns 3(沒有指明 fromIndex 則從末尾 l 處開始反向檢索到的第一個(gè) a 出現(xiàn)在 l 的后面,即 index 為 3 的位置) 'canal'.lastIndexOf('a', 2); // returns 1(指明 fromIndex 為 2 則從 n 處反向向回檢索到其后面就是 a,即 index 為 1 的位置) 'canal'.lastIndexOf('a', 0); // returns -1(指明 fromIndex 為 0 則從 c 處向左回向檢索 a 發(fā)現(xiàn)沒有,故返回-1) 'canal'.lastIndexOf('x'); // returns -1 'canal'.lastIndexOf('c', -5); // returns 0(指明 fromIndex 為-5 則視同 0,從 c 處向左回向查找發(fā)現(xiàn)自己就是,故返回 0) 'canal'.lastIndexOf('c', 0); // returns 0(指明 fromIndex 為 0 則從 c 處向左回向查找 c 發(fā)現(xiàn)自己就是,故返回自己的索引 0) 'canal'.lastIndexOf(''); // returns 5 'canal'.lastIndexOf('', 2); // returns 2
6、startsWith()
用來判斷當(dāng)前字符串是否以另外一個(gè)給定的子字符串開頭,并根據(jù)判斷結(jié)果返回 true 或 false
const str1 = 'Saturday night plans'; console.log(str1.startsWith('Sat')); // expected output: true console.log(str1.startsWith('Sat', 3)); // expected output: false
7、endsWith()
用來判斷當(dāng)前字符串是否是以另外一個(gè)給定的子字符串“結(jié)尾”的,根據(jù)判斷結(jié)果返回 true 或 false
var str = "To be, or not to be, that is the question."; alert( str.endsWith("question.") ); // true alert( str.endsWith("to be") ); // false alert( str.endsWith("to be", 19) ); // true
8、includes()
用于判斷一個(gè)字符串是否包含在另一個(gè)字符串中,根據(jù)情況返回 true 或 false
var str = 'To be, or not to be, that is the question.'; console.log(str.includes('To be')); // true console.log(str.includes('question')); // true console.log(str.includes('nonexistent')); // false console.log(str.includes('To be', 1)); // false console.log(str.includes('TO BE')); // false
總結(jié)一下:
上面介紹的8個(gè)方法,大致分為三類:
- 字符串指定位置的字符或者字符編碼:
charAt
,charCodeAt
,codePointAt
- 返回字符串中指定子串的位置或最后位置:
indexOf
,lastIndexOf
- 字符串是否以指定字符串開始、結(jié)束或包含指定字符串:
startsWith
,endsWith
,includes
9、concat()
將一個(gè)或多個(gè)字符串與原字符串連接合并,形成一個(gè)新的字符串并返回。
let hello = 'Hello, ' console.log(hello.concat('Kevin', '. Have a nice day.')) // Hello, Kevin. Have a nice day. let greetList = ['Hello', ' ', 'Venkat', '!'] "".concat(...greetList) // "Hello Venkat!" "".concat({}) // [object Object] "".concat([]) // "" "".concat(null) // "null" "".concat(true) // "true" "".concat(4, 5) // "45"
10、fromCharCode()
靜態(tài) String.fromCharCode() 方法返回由指定的 UTF-16 代碼單元序列創(chuàng)建的字符串。
String.fromCharCode(65, 66, 67); // 返回 "ABC" String.fromCharCode(0x2014); // 返回 "—" String.fromCharCode(0x12014); // 也是返回 "—"; 數(shù)字 1 被剔除并忽略 String.fromCharCode(8212); // 也是返回 "—"; 8212 是 0x2014 的十進(jìn)制表示
11、fromCodePoint()
String.fromCodePoint() 靜態(tài)方法返回使用指定的代碼點(diǎn)序列創(chuàng)建的字符串。
String.fromCodePoint(42); // "*" String.fromCodePoint(65, 90); // "AZ" String.fromCodePoint(0x404); // "\u0404" String.fromCodePoint(0x2F804); // "\uD87E\uDC04" String.fromCodePoint(194564); // "\uD87E\uDC04" String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07" String.fromCodePoint('_'); // RangeError String.fromCodePoint(Infinity); // RangeError String.fromCodePoint(-1); // RangeError String.fromCodePoint(3.14); // RangeError String.fromCodePoint(3e-2); // RangeError String.fromCodePoint(NaN); // RangeError
12、split()
使用指定的分隔符字符串將一個(gè)String對象分割成子字符串?dāng)?shù)組,以一個(gè)指定的分割字串來決定每個(gè)拆分的位置。
const str = 'The quick brown fox jumps over the lazy dog.'; const words = str.split(' '); console.log(words[3]); // expected output: "fox" const chars = str.split(''); console.log(chars[8]); // expected output: "k" const strCopy = str.split(); console.log(strCopy); // expected output: Array ["The quick brown fox jumps over the lazy dog."]
13、slice()
提取某個(gè)字符串的一部分,并返回一個(gè)新的字符串,且不會(huì)改動(dòng)原字符串
const str = 'The quick brown fox jumps over the lazy dog.'; console.log(str.slice(31)); // expected output: "the lazy dog." console.log(str.slice(4, 19)); // expected output: "quick brown fox" console.log(str.slice(-4)); // expected output: "dog." console.log(str.slice(-9, -5)); // expected output: "lazy"
14、substring()
返回一個(gè)字符串在開始索引到結(jié)束索引之間的一個(gè)子集,或從開始索引直到字符串的末尾的一個(gè)子集。
var anyString = "Mozilla"; // 輸出 "Moz" console.log(anyString.substring(0,3)); console.log(anyString.substring(3,0)); console.log(anyString.substring(3,-3)); console.log(anyString.substring(3,NaN)); console.log(anyString.substring(-2,3)); console.log(anyString.substring(NaN,3)); // 輸出 "lla" console.log(anyString.substring(4,7)); console.log(anyString.substring(7,4)); // 輸出 "" console.log(anyString.substring(4,4)); // 輸出 "Mozill" console.log(anyString.substring(0,6)); // 輸出 "Mozilla" console.log(anyString.substring(0,7)); console.log(anyString.substring(0,10));
15、substr()
返回一個(gè)字符串中從指定位置開始到指定字符數(shù)的字符(注意:該方法可能會(huì)被廢棄,使用substring代替)
var str = "abcdefghij"; console.log("(1,2): " + str.substr(1,2)); // (1,2): bc console.log("(-3,2): " + str.substr(-3,2)); // (-3,2): hi console.log("(-3): " + str.substr(-3)); // (-3): hij console.log("(1): " + str.substr(1)); // (1): bcdefghij console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab console.log("(20, 2): " + str.substr(20,2)); // (20, 2):
匯總一下:
- concat:連接兩個(gè)字符串并返回新的字符串。
- fromCharCode, fromCodePoint:從指定的 Unicode 值序列構(gòu)造一個(gè)字符串。這是一個(gè) String 類方法,不是實(shí)例方法。
- split:通過將字符串分離成一個(gè)個(gè)子串來把一個(gè) String 對象分裂到一個(gè)字符串?dāng)?shù)組中。
- slice:從一個(gè)字符串提取片段并作為新字符串返回。
- substring, substr:分別通過指定起始和結(jié)束位置,起始位置和長度來返回字符串的指定子集。
16、match()
檢索返回一個(gè)字符串匹配正則表達(dá)式的結(jié)果。
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; const regex = /[A-Z]/g; const found = paragraph.match(regex); console.log(found); // expected output: Array ["T", "I"]
17、replace()
返回一個(gè)由替換值(replacement)替換部分或所有的模式(pattern)匹配項(xiàng)后的新字符串。模式可以是一個(gè)字符串或者一個(gè)正則表達(dá)式,替換值可以是一個(gè)字符串或者一個(gè)每次匹配都要調(diào)用的回調(diào)函數(shù)。如果pattern是字符串,則僅替換第一個(gè)匹配項(xiàng)
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; console.log(p.replace('dog', 'monkey')); // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?" const regex = /Dog/i; console.log(p.replace(regex, 'ferret')); // expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
18、search()
執(zhí)行正則表達(dá)式和 String 對象之間的一個(gè)搜索匹配
var str = "hey JudE"; var re = /[A-Z]/g; var re2 = /[.]/g; console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J" console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation
19、toLowerCase()
會(huì)將調(diào)用該方法的字符串值轉(zhuǎn)為小寫形式,并返回。
console.log('中文簡體 zh-CN || zh-Hans'.toLowerCase()); // 中文簡體 zh-cn || zh-hans console.log( "ALPHABET".toLowerCase() ); // "alphabet"
20、toUpperCase()
將調(diào)用該方法的字符串轉(zhuǎn)為大寫形式并返回(如果調(diào)用該方法的值不是字符串類型會(huì)被強(qiáng)制轉(zhuǎn)換)。
const sentence = 'The quick brown fox jumps over the lazy dog.'; console.log(sentence.toUpperCase()); // expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
21、normalize()
會(huì)按照指定的一種 Unicode 正規(guī)形式將當(dāng)前字符串正規(guī)化。(如果該值不是字符串,則首先將其轉(zhuǎn)換為一個(gè)字符串)
const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065'; const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065'; console.log(`${name1}, ${name2}`); // expected output: "Amélie, Amélie" console.log(name1 === name2); // expected output: false console.log(name1.length === name2.length); // expected output: false const name1NFC = name1.normalize('NFC'); const name2NFC = name2.normalize('NFC'); console.log(`${name1NFC}, ${name2NFC}`); // expected output: "Amélie, Amélie" console.log(name1NFC === name2NFC); // expected output: true console.log(name1NFC.length === name2NFC.length); // expected output: true
22、repeat()
構(gòu)造并返回一個(gè)新字符串,該字符串包含被連接在一起的指定數(shù)量的字符串的副本
"abc".repeat(-1) // RangeError: repeat count must be positive and less than inifinity "abc".repeat(0) // "" "abc".repeat(1) // "abc" "abc".repeat(2) // "abcabc" "abc".repeat(3.5) // "abcabcabc" 參數(shù) count 將會(huì)被自動(dòng)轉(zhuǎn)換成整數(shù)。 "abc".repeat(1/0) // RangeError: repeat count must be positive and less than inifinity ({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2) //"abcabc",repeat 是一個(gè)通用方法,也就是它的調(diào)用者可以不是一個(gè)字符串對象。
23、trim()
會(huì)從一個(gè)字符串的兩端刪除空白字符。在這個(gè)上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行終止符字符(如 LF,CR 等)
var orig = ' foo '; console.log(orig.trim()); // 'foo' // 另一個(gè) .trim() 例子,只從一邊刪除 var orig = 'foo '; console.log(orig.trim()); // 'foo'
匯總一下:
- match, replace, search:通過正則表達(dá)式來工作。
- toLowerCase, toUpperCase:分別返回字符串的小寫表示和大寫表示。
- normalize:按照指定的一種 Unicode 正規(guī)形式將當(dāng)前字符串正規(guī)化。
- repeat:將字符串內(nèi)容重復(fù)指定次數(shù)后返回。
- trim:去掉字符串開頭和結(jié)尾的空白字符。
到此這篇關(guān)于梳理總結(jié)JavaScript的23個(gè)String方法的文章就介紹到這了,更多相關(guān)JS String方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Javascript表單驗(yàn)證要注意的事項(xiàng)
JavaScript 可用來在數(shù)據(jù)被送往服務(wù)器前對 HTML 表單中的這些輸入數(shù)據(jù)進(jìn)行驗(yàn)證。被 JavaScript 驗(yàn)證的這些典型的表單數(shù)據(jù)有:用戶是否已填寫表單中的必填項(xiàng)目?用戶輸入的郵件地址是否合法?用戶是否已輸入合法的日期?用戶是否在數(shù)據(jù)域 (numeric field) 中輸入了文本?2014-09-09JavaScript數(shù)組去重的3種方法和代碼實(shí)例
這篇文章主要介紹了JavaScript數(shù)組去重的3種方法和代碼實(shí)例,本文直接給出實(shí)例代碼,需要的朋友可以參考下2015-07-07JavaScript 自動(dòng)分號插入(JavaScript synat:auto semicolon insertion)
今天在看《Extjs中文手冊》的時(shí)候,寫了四五行樣例代碼,結(jié)果IE和Firefox一直報(bào)錯(cuò)不通過。2009-11-11JS實(shí)現(xiàn)網(wǎng)頁上隨滾動(dòng)條滾動(dòng)的層效果代碼
這篇文章主要介紹了JS實(shí)現(xiàn)網(wǎng)頁上隨滾動(dòng)條滾動(dòng)的層效果代碼,涉及JavaScript頁面元素屬性的獲取、運(yùn)算及設(shè)置等操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11JS判斷鼠標(biāo)進(jìn)入容器的方向與window.open新窗口被攔截的問題
這篇文章主要給大家介紹了利用Javascript判斷鼠標(biāo)進(jìn)入容器方向的方法,以及window.open新窗口被攔截的問題分析,文中給出了詳細(xì)圖文介紹和示例代碼,相信對大家的理解和學(xué)習(xí)具有一定的參考借鑒價(jià)值,下面來一起看看吧。2016-12-12javascript動(dòng)態(tài)生成樹形菜單的方法
這篇文章主要介紹了javascript動(dòng)態(tài)生成樹形菜單的方法,涉及JavaScript針對頁面元素與屬性的動(dòng)態(tài)操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11js創(chuàng)建元素(節(jié)點(diǎn))示例
本文為大家介紹下使用js是如何創(chuàng)建元素(節(jié)點(diǎn))的,感興趣的朋友不要錯(cuò)過2014-01-01