文章目錄
js數組和字符串方法(2)—查找類__常用字符串方法
charAt(index)
概述
charAt() 方法從一個字符串中返回指定的字符。
參數
index
一個介於0 和字符串長度減1之間的整數。 (0~length-1)
如果沒有提供索引,charAt() 將使用0。
描述
字符串中的字符從左向右索引,第一個字符的索引值爲 0,最後一個字符(假設該字符位於字符串 stringName 中)的索引值爲 stringName.length - 1
。 如果指定的 index 值超出了該範圍,則返回一個空字符串。
實例及注意事項
var str = 'abcdefg';
console.log(str[1]);
console.log(str.charAt(2));
注意:通過str[index] 這樣的方式取值,是有兼容問題的,IE8以下是無法使用的
var str = 'abcdefg';
console.log(str.charAt())
console.log(str.charAt(str.length+2));
console.log(str.charAt(-5));
輸出字符串中不同位置的字符
下例輸出字符串 “Brave new world
” 不同位置處的字符:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
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) + "'");
</script>
</body>
</html>
charCodeAt(index)
charCodeAt()
方法返回0到65535之間的整數,表示給定索引處的UTF-16代碼單元 (在 Unicode 編碼單元表示一個單一的 UTF-16 編碼單元的情況下,UTF-16 編碼單元匹配 Unicode 編碼單元。但在——例如 Unicode 編碼單元 > 0x10000 的這種——不能被一個 UTF-16 編碼單元單獨表示的情況下,只能匹配 Unicode 代理對的第一個編碼單元) 。如果你想要整個代碼點的值,使用 codePointAt()
。
簡單而言:用於獲取當前字符串的unicode編碼
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log(`The character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index)}`);
// expected output: "The character code 113 is equal to q"
> “The character code 113 is equal to q”
參數
index
: 一個大於等於 0,小於字符串長度的整數。如果不是一個數值,則默認爲 0。
返回值
返回值是一表示給定索引處(String中index索引處)字符的 UTF-16 代碼單元值的數字;如果索引超出範圍,則返回 NaN
。
描述
Unicode 編碼單元(code points)的範圍從 0 到 1,114,111(0x10FFFF)。開頭的 128 個 Unicode 編碼單元和 ASCII 字符編碼一樣。關於 Unicode 的更多信息,可查看 JavaScript Guide。
如果指定的 index 小於 0 或不小於字符串的長度,則 charCodeAt
返回 NaN
。
實例及注意事項
針對字符串比較,實際比較大小是ASCII編碼
var str = "kkkkkk";// k - 107
var str2 = "v"; //v - 118
console.log(str > str2);
除此之外還可以比較中文:
實際上如果比較字符串,比較的是Unicode編碼的大小
var china1 = "中";
var china2 = "文中";
console.log(china1 > china2);
console.log(china1.charCodeAt());
console.log(china2.charCodeAt());//20013 25991
console.log(china2.charCodeAt(-10));
fromCharCode
靜態 String.fromCharCode()
方法返回由指定的UTF-16代碼單元序列創建的字符串。
console.log(String.fromCharCode(189, 43, 190, 61));
// expected output: "½+¾="
> “½+¾=”
參數
num1, ..., numN
: 一系列UTF-16代碼單元的數字。 範圍介於0到65535(0xFFFF)之間。 大於0xFFFF的數字將被截斷。 不進行有效性檢查。
返回值
一個長度爲N的字符串,由N個指定的UTF-16代碼單元組成
描述
該方法返回一個字符串,而不是一個 String
對象。
由於 fromCharCode()
是 String
的靜態方法,所以應該像這樣使用:String.fromCharCode()
,而不是作爲你創建的 String
對象的方法
實例及注意事項
var str="我愛你";
var arr = []
for(var i=0;i<str.length;i++){
// console.log(str.charCodeAt(i));
arr[i] = str.charCodeAt(i);
}
console.log(arr);
console.log(String.fromCharCode(arr[0], arr[1], arr[2]));
console.log(String.fromCharCode(arr[1]));
console.log(String.fromCharCode(arr[2]));
indexOf
indexOf()
方法返回調用它的 String
對象中第一次出現的指定值的索引,從 fromIndex
處進行搜索。如果未找到該值,則返回 -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"
> “The index of the first “dog” from the beginning is 40”
> “The index of the 2nd “dog” is 52”
語法
str.indexOf(searchValue [, fromIndex])
參數
searchValue
要被查找的字符串值。
如果沒有提供確切地提供字符串,searchValue 會被強制設置爲 "undefined"
, 然後在當前字符串中查找這個值。
舉個例子:'undefined'.indexOf()
將會返回0,因爲 undefined
在位置0處被找到,但是 'undefine'.indexOf()
將會返回 -1 ,因爲字符串 'undefined'
未被找到。
fromIndex
可選
數字表示開始查找的位置。可以是任意整數,默認值爲 0
。
如果 fromIndex
的值小於 0
,或者大於 str.length
,那麼查找分別從 0
和str.length
開始。(注: fromIndex
的值小於 0
,等同於爲空情況; fromIndex
的值大於 str.length
,那麼結果會直接返回 -1
。)
舉個例子,'hello world'.indexOf('o', -5)
返回 4
,因爲它是從位置0
處開始查找,然後 o
在位置4
處被找到。另一方面,'hello world'.indexOf('o', 11)
(或 fromIndex
填入任何大於11
的值)將會返回 -1
,因爲開始查找的位置11
處,已經是這個字符串的結尾了。
返回值
查找的字符串 searchValue
的第一次出現的索引,如果沒有找到,則返回 -1
。
若被查找的字符串 searchValue
是一個空字符串,將會產生“奇怪”的結果。如果 fromIndex
值爲空,或者 fromIndex
值小於被查找的字符串的長度,返回值和以下的 fromIndex
值一樣:
'hello world'.indexOf('') // 返回 0
'hello world'.indexOf('', 0) // 返回 0
'hello world'.indexOf('', 3) // 返回 3
'hello world'.indexOf('', 8) // 返回 8
另外,如果 fromIndex
值大於等於字符串的長度,將會直接返回字符串的長度(str.length
):
'hello world'.indexOf('', 11) // 返回 11
'hello world'.indexOf('', 13) // 返回 11
'hello world'.indexOf('', 22) // 返回 11
從前面一個例子可以看出,被查找的值是空值時,Javascript將直接返回指定的索引值。從後面一個例子可以看出,被查找的值是空值時,Javascript將直接返回字符串的長度。
描述值
字符串中的字符被從左向右索引。第一個字符的索引(index)是 0
,變量名爲 stringName
的字符串的最後一個字符的索引是 stringName.length - 1
。
"Blue Whale".indexOf("Blue") // 返回 0
"Blue Whale".indexOf("Blute") // 返回 -1
"Blue Whale".indexOf("Whale", 0) // 返回 5
"Blue Whale".indexOf("Whale", 5) // 返回 5
"Blue Whale".indexOf("", -1) // 返回 0
"Blue Whale".indexOf("", 9) // 返回 9
"Blue Whale".indexOf("", 10) // 返回 10
"Blue Whale".indexOf("", 11) // 返回 10
indexOf
方法是區分大小寫的。例如,下面的表達式將返回 -1
:
"Blue Whale".indexOf("blue") // 返回 -1
檢測是否存在某字符串
注意 0
並不會被當成 true
,-1
不會被當成 false
。所以當檢測某個字符串是否存在於另一個字符串中時,可使用下面的方法:
'Blue Whale'.indexOf('Blue') !== -1 // true
'Blue Whale'.indexOf('Bloe') !== -1 // false
~('Blue Whale'.indexOf('Bloe')) // 0, 這是一種錯誤用法
實例及注意事項
var str = "aabbccddeeffggabcdefg";
console.log(str.indexOf('b'));
console.log(str.indexOf('ff'));
console.log(str.indexOf('f',14));//19
console.log(str.indexOf('a', -1));
console.log(str.indexOf('k', 50));
使用indexOf()
和 lastIndexOf()
下例使用 indexOf()
和 lastIndexOf()
方法定位字符串中 “Brave new world
” 的值。
var anyString = "Brave new world";
console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
// logs 8
console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
// logs 10
console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
// logs 6
console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
// logs 6
indexOf
和區分大小寫
下例定義了兩個字符串變量。兩個變量包含相同的字符串,除了第二個字符串中的某些字符爲大寫。第一個 log
方法輸出 19。但是由於 indexOf
方法區分大小寫,因此不會在 myCapString
中發現字符串 “cheddar"
,所以,第二個 log
方法會輸出 -1。
var myString = "brie, pepper jack, cheddar";
var myCapString = "Brie, Pepper Jack, Cheddar";
console.log('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar"));
// logs 19
console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar"));
// logs -1
使用 indexOf
統計一個字符串中某個字母出現的次數
在下例中,設置了 count
來記錄字母 e
在字符串 str
中出現的次數:
// 翻譯:生存還是毀滅?這是個問題。(莎士比亞《哈姆雷特》)
var str = 'To be, or not to be, that is the question.';
var count = 0;
var pos = str.indexOf('e');
while (pos !== -1) {
count++;
pos = str.indexOf('e', pos + 1);
}
console.log(count); // displays 4
lastIndexOf
lastIndexOf()
方法返回調用String
對象的指定值最後一次出現的索引,在一個字符串中的指定位置 fromIndex
處從後向前搜索。如果沒找到這個特定值則返回-1 。
該方法將從尾到頭地檢索字符串 str,看它是否含有子串 searchValue。開始檢索的位置在字符串的 fromIndex 處或字符串的結尾(沒有指定 fromIndex 時)。如果找到一個 searchValue,則返回 searchValue 的第一個字符在 str 中的位置。str中的字符位置是從 0 開始的。
語法
str.lastIndexOf(searchValue[, fromIndex])
參數
searchValue
一個字符串,表示被查找的值。如果searchValue
是空字符串,則返回fromIndex
。
fromIndex
待匹配字符串searchValue的開頭一位字符從 str的第fromIndex位開始向左迴向查找。fromIndex
默認值是 str.length
。如果 fromIndex >= str.length
,則會搜索整個字符串。如果 fromIndex < 0
,則等同於 fromIndex == 0
。
返回值
返回指定值最後一次出現的索引(該索引仍是以從左至右0開始記數的),如果沒找到則返回-1。
描述
字符串中的字符被從左向右索引。首字符的索引(index)是 0,最後一個字符的索引是 stringName.length - 1
。
'canal'.lastIndexOf('a'); // returns 3 (沒有指明fromIndex則從末尾l處開始反向檢索到的第一個a出現在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發現沒有,故返回-1)
'canal'.lastIndexOf('x'); // returns -1
'canal'.lastIndexOf('c', -5); // returns 0(指明fromIndex爲-5則視同0,從c處向左迴向查找發現自己就是,故返回0)
'canal'.lastIndexOf('c', 0); // returns 0(指明fromIndex爲0則從c處向左迴向查找c發現自己就是,故返回自己的索引0)
'canal'.lastIndexOf(''); // returns 5
'canal'.lastIndexOf('', 2); // returns 2
Note: 'abab'.lastIndexOf('ab', 2)
將返回 2 而不是 0, 因爲fromIndex只限制待匹配字符串的開頭。
(例如’abadefgabm’.lastIndexOf(‘ab’, 7) 返回7,雖然查找的’ab’中的b已經在 index=8的位置了從index=7的a處向左查找仍是能找到自身a加上其後連成ab,因爲fromIndex指的是待匹配字符串的開頭那一個)
區分大小寫
lastIndexOf
方法區分大小寫。例如,下面的表達式返回 -1:
"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1
實例及注意事項
var str= "kaichele";
console.log(str.lastIndexOf("k", str.length));
console.log(str.lastIndexOf("k", -50));
console.log(str.lastIndexOf("vv"));
使用 indexOf
和 lastIndexOf
下例使用 indexOf
和 lastIndexOf
方法來定位字符串 “Brave new world
” 中的值。
var anyString = "Brave new world";
console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
// Displays 8
console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
// Displays 10
console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
// Displays 6
console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
// Displays 6
(後續待補充)