天天看點

MDN - 字元串API筆記

傳送門

String.prototype.charAt(index)

從一個字元串中傳回指定的字元。

index 一個介于0 和字元串長度減1之間的整數。預設值為0

index 從 0 開始 空格是占一個位置的

擷取一個超出字元串長度的位置,則傳回空格 不報錯

var anyString = "Brave new world";
console.log(anyString.charAt(0)); // B

// 差別:通過字元串下标擷取
console.log(anyString[1]); // B
console.log(anyString[100]); // undefined
           

String.prototype.charCodeAt(index)

傳回字元串指定位置的字元編碼

用于鍵盤事件

區分大小寫的

index 超出位置 傳回 NaN

空格的編碼号 32

String.fromCharCode(unicode 編碼)

把對應的編碼還原字元串

var str = "I love you bady";
    var codeArr = [];
    for (var index in str) {
      codeArr.push(str.charCodeAt(index));
    }
    console.log(codeArr);
    var s = "";
    for (var index in codeArr) {
      s += String.fromCharCode(codeArr[index]);
    }
    console.log(s);
           

String.prototype.indexOf(searchValue [, fromIndex])

傳回調用它的String 中第一次出現的指定值的索引,從 fromIndex 處進行搜尋。如果未找到該值,則傳回 -1

searchValue 要被查找的字元串值。如果沒有提供确切地提供字元串,searchValue 會被強制設定為 “undefined” (會将傳入的值轉化成字元串)

fromIndex 數字表示開始查找的位置。可以是任意整數,預設值為 0。

'undefined'.indexOf(); // 0
'null'.indexOf(null); // 0
           

String.prototype.lastIndexOf(searchValue[, fromIndex])

傳回調用 String 的指定值最後一次出現的索引,在一個字元串中的指定位置 fromIndex處從後向前搜尋。如果沒找到這個特定值則傳回-1

searchValue 一個字元串,表示被查找的值。如果searchValue是空字元串,則傳回fromIndex。

fromIndex 待比對字元串從str的第fromIndex位開始向左回向查找

'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
           

String.prototype.concat(str2, [, ...strN])

将一個或多個字元串與原字元串連接配接合并,形成一個新的字元串并傳回

str2 [, …strN] 需要連接配接到 str 的字元串。
var hello = 'Hello, '
console.log(hello.concat('Kevin', '. Have a nice day.')) // Hello, Kevin. Have a nice day.
           

String.prototype.split([separator[, limit]])

使用指定的分隔符字元串将一個String對象分割成子字元串數組,以一個指定的分割字串來決定每個拆分的位置

separator 指定表示每個拆分應發生的點的字元串。如果傳遞空字元串則拆分每個字母

limit 一個整數,限定傳回的分割片段數量。

var myString = "Hello World. How are you doing?";
var splits = myString.split(" ", 3);
console.log(splits); // ["Hello", "World.", "How"]

"hello world".split('l') // ["he","","o wor","d"]

"hello world".split('') // ["h","e","l","l","o"," ","w","o","r","l","d"]
           

補充:

var str5 = "I ,wan,t to se,e the sun-raise with you";
 var newArr = str5.split(" ");
 console.log("split拆分==>", newArr)
 console.log("用split進行分割,會不會對原變量造成影響==>", str5)   // 不會
           

String.prototype.slice(beginIndex[, endIndex])

提取某個字元串的一部分,并傳回一個新的字元串,且不會改動原字元串

beginIndex 從該索引(以 0 為基數)處開始提取原字元串中的字元。如果值為負數則倒數

endIndex 在該索引處結束前提取字元串**(不包含次索引處字元)**,如果省略該參數,slice() 會一直提取到字元串末尾。可以為負

var str6 = "用錢買開心,很開心!";
console.log("slice測試==>", str6.slice(1, 3)) // 錢買 (不包括索引3指向的“開”)
console.log("slice測試==>", str6.slice(4, 9)) // 心,,很開心(索引值超出長度的,不用被理會,不會報錯)
console.log("slice測試==>", str6.slice(2, -4))// 買開心, 如果第二個參數是負數,那麼它規定的是從數組尾部開始算起的元素
console.log("slice測試==>", str6.slice(-5, -2))// ,很開    負數, 倒數位數,倒數第5個開始到倒數第2個 輸出資料
console.log("slice測試==>", str6.slice(2))    // 買開心,很開心!
           

注: 負數是從右到左開始,負多少,就先左數多少。(從一開始數)

String.prototype.substring(indexStart[, indexEnd])

傳回一個字元串在開始索引到結束索引之間的一個子集, 或從開始索引直到字元串的末尾的一個子集。

indexStart 需要截取的第一個字元的索引,該索引位置的字元作為傳回的字元串的首字母。

indexEnd 一個 0 到字元串長度之間的整數,以該數字為索引的字元不包含在截取的字元串内。若省略該屬性substring 提取字元一直到字元串末尾。

注意:indexStart 和 indexEnd 數小于 0 或為 NaN,則被當作 0。

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));
           

String.prototype.substr(start[, length])

傳回一個字元串中從指定位置開始到指定字元數的字元。

start 開始提取字元的位置。如果為負值,則倒數

length 提取的字元數。

注意:該方法未來将要被舍棄請盡量避免使用該方法,使用substring替代它

var str = "abcdefghij";
console.log(str.substr(1,2));   // bc
console.log(str.substr(-3,2));  //  hi
console.log((str.substr(-3));    //  hij
console.log(str.substr(1));     //  bcdefghij
console.log(str.substr(-20,2)); //  ab
console.log(str.substr(20,2));  // 
           

String.prototype.replace(substr, newSubStr|function)

傳回一個由替換值替換部分或所有的substr模式比對項後的新字元串

substr 一個将被 newSubStr 替換的 字元串。

newSubStr 用于替換掉第一個參數在原字元串中的比對部分的字元串。

function 一個用來建立新子字元串的函數,該函數的傳回值将替換掉第一個參數比對到的結果。

var re = "apples";
var str = "apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges"); // "oranges are round, and apples are juicy."

var re = "apples";
var str = "apples are round, and apples are juicy.";
// 給指定單詞加引号
var newstr = str.replace(re, function(match) {
    // match 是比對到的子串。
    return '"' + match + '"' 
}) // '"Apples" are round, and apples are juicy.'
           

String.prototype.replaceAll(substr, newSubstr|function)

一個新字元串,新字元串所有滿足 pattern 的部分都已被replacement 替換

String.prototype.toLowerCase()

會将調用該方法的字元串值轉為小寫形式,并傳回。

String.prototype.toUpperCase()

會将調用該方法的字元串轉為大寫形式并傳回

String.prototype.repeat(count)

構造并傳回一個新字元串,該字元串包含被連接配接在一起的指定數量的字元串的副本

count介于 0 和 +Infinity 之間的整數。表示在新構造的字元串中重複了多少遍原字元串。
"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" 參數count将會被自動轉換成整數.
"abc".repeat(1/0)    // RangeError: repeat count 必須大于等于 0 且 小于+inifinity
           

String.prototype.trim()

會從一個字元串的兩端删除空白字元。在這個上下文中的空白字元是所有的空白字元 (space, tab, no-break space 等)

var orig1 = '   foo  ';
console.log(orig1.trim()); // 'foo'

var orig2 = 'foo    ';
console.log(orig2.trim()); // 'foo'
           

ES6 的字元串方法

ES6學習筆記三:字元串

應用于正規表達式

String.prototype.match()

String.prototype.matchAll()

String.prototype.search()

String.prototype.toString()

傳回指定對象的字元串形式

var x = new String("Hello world");

alert(x.toString())      // 輸出 "Hello world"
           

String.prototype.valueOf()

傳回 String 對象的原始值

const stringObj = new String('foo');

console.log(stringObj);
// expected output: String { "foo" }

console.log(stringObj.valueOf());
// expected output: "foo"
           

String.prototype.localeCompare()

歡迎通路的我個人部落格