常用Js string方法筆記

source:un
source:unplash

寫在前面:

字串可解悉為字數(length),字串內索引值(index),字串索引值由0開始,最後字元索引值為字數減1(length-1)。詳細操控方法記錄於下。

string為變數值,記錄於下:

let string = ‘abcdef’;

1. 取得字串長度(length):

取出字串長度,回傳值為【數字】。

string.length; //output:6

2. 轉換為字串(toString):

string.toString(); //output:'string'

3. 由索引值取出字串內字符(charAt):

string.charAt(index)方法等於string[index]。

string.charAt(index); //範圍為0~length-1
string.charAt(2); //output: 'c'

4. 結合字串(concat):

結合字串方式,可利用以下兩種方式執行:

let string1 = 'ghijk';
string.concat(string1); //output: 'abcdefghijk';
string.concat(' ', string1); //output: 'abcdef ghijk';

5. 搜尋字串包含(includes):

string.includes(string, index),回傳值為【布林值】

string為需找尋的部份字串

Index為指定索引值(可選填)

string.includes('a');    //output:true  (字串內容含有’a’)
string.includes('a',1); //output:false (字串內第二字元以後不含’a’)

6. 字串指定值索引(indexOf):

string.indexOf(string, index),回傳值為【數字】

string為需找尋的部份字串

Index為從指定索引開始(可選填)

string.indexOf('a');   //output:0  (a位於字串中第一個)
string.indexOf('a',1); //output:-1 (由第二個字後找不到a)

7. 提取並回傳新字串(slice):

string.slice(beginIndex,endIndex),回傳值為【字串】

beginIndex為起始索引值

endIndex為結束索引值(可選填)

//index正值為由頭開始取;負值為由尾開始取
string.slice(2); //output:'cdef' (從頭開始,由第三字元開始取)
string.slice(2,3); //output:'c' (從頭開始,由第三字元取至第四字元)
string.slice(-3); //output:'def' (從尾開始,由倒數第三字元取到底為止)
string.slice(-3,-1);//output:'de' (從尾開始,由倒數第三字元取到倒數第一)

8. 字串分割(split)

string.split(string,limit),回傳為【arr1 , arr2 , arr3,….】

string為分割符號

limit為回傳陣列長度限制(可選填)

let string = a,b,c,d,e,f,g;
string.split(','); //output:[“a”,“b”,“c”,“d”,“e”,“f”,“g”]
string.split(',', 2); //output:[“a”,“b”] (取得長度限制為兩個)

9. 字串取代(replace)

搜尋字串中指定字符,取代指定字串,回傳值為【字串】

string.replace(searchStr, replaceStr);

searchStr為搜尋取代字串

replaceStr為需取代字串

string.replace('a','a1234');  //output:'a1234bcdef'

10. 尋找字串符合的字元(match)

string.match(regex),回傳為符合條件的陣列

regex為正則表示法

let str="1 plus 2 equal 3";
str.match(/\d+/g); //output:由字串中取出數字,回傳陣列為['1','2','3'];

--

--