Javascript中字符串方法總結

原文連接:https://mrzhang123.github.io/...git

字符方法

chartAt()與charCodeAt()

參數:基於0的字符位置github

chartAt()以單字符字符串的形式返回給定位置的那個字符。而charCodeAt()返回的是字符編碼。正則表達式

var stringValue = 'hello world';
/*chartAt()*/
console.log(stringValue.chartAt(1));    // 'e'

字符串操做方法

concat()(數組中也有該方法)

參數:一個或多個字符串數組

將一個會多個字符串拼接起來,固然更經常使用的是使用 「+」 進行拼接函數

substring()與slice()(數組中也有此方法)

參數:指定子字符串的開始位置子字符串到哪裏結束編碼

做用:建立新的子字符串(能夠理解爲字符串截取)spa

substr()

參數:指定子字符串的開始位置返回的子字符串的字符個數code

做用:建立新的子字符串(能夠理解爲字符串截取)對象

repeat()(ES6新增)

參數:數字(表示重複的次數)blog

做用:將原字符串重複n次

若是傳入負數,則報錯,傳入小數和NaN等同於傳入0

substring,slice,substr,repeat均返回子字符串,不會修改原來的字符串

var stringValue = "hello world"; 
alert(stringValue.slice(3));          //"lo world" 
alert(stringValue.substring(3));      //"lo world" 
alert(stringValue.substr(3));         //"lo world" 
alert(stringValue.slice(3, 7));       //"lo w" 
alert(stringValue.substring(3,7));    //"lo w" 
alert(stringValue.substr(3, 7));      //"lo worl" 
/*repeat()*/
var a = 'he';
var b = a.repeat(3);
console.log(`${a}---${b}`); /          //"he---hehehe"

當給這三個方法傳入負值的時候,三個的表現不一樣:

  • slice()會將傳入的負值與字符串的長度相加

  • substr()會將第一個位置的負值參數加上字符串長度後轉爲正數,而第二個位置的負值將轉化爲0

  • substring()會把全部的負參數轉化爲0

  • repeat()會報錯

字符串位置方法

indexOf()和lastIndexOf()(數組中也有該方法)

參數:要搜索的子字符串開始搜索的位置(可選)

搜索給定的子字符串,若是找到則返回位置,不然返回-1

var stringValue = "hello world"; 
alert(stringValue.indexOf("o"));             //4 
alert(stringValue.lastIndexOf("o"));         //7

這兩個方法在搜索到第一個匹配的子字符串後就中止運行,因此若是想找到字符串中全部的
子字符串出現的位置,能夠循環調用indexOflastIndexOf

var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"; 
var positions = new Array(); 
var pos = stringValue.indexOf("e"); 
 
while(pos > -1){ 
    positions.push(pos); 
    pos = stringValue.indexOf("e", pos + 1); 
} 
     
alert(positions);    //"3,24,32,35,52"

ES6新增includes()、startsWith()、endsWith()

  • includes():返回布爾值,表示是否找到了參數字符串

  • startsWith():返回布爾值,表示參數字符串是否在源字符串的頭部

  • endsWith():返回布爾值,表示參數字符串是否在源字符串的尾部

這三個方法的參數與indexOf()lastIndexOf()同樣

var s = 'Hello world';
s.startsWith('world',6);    // true
s.endsWith('Hello',5);        // true
s.includes('Hello',6);        //false

注意:
使用第2個參數n時,endsWith的行爲與其餘兩個方法有所不一樣。它針對前面n個字符,而其餘兩個方法針對從第n個位置開始直到字符串結束的字符。

去空格--trim()

ES5中新增trim()方法用於去除字符串的左右空格,該方法會建立一個字符串的副本,不會改變原有的字符串,此外,Firefox 3.5+、Safari 5+
和 Chrome 8+還支持非標準的 trimLeft()和 trimRight()方法,分別用於刪除字符串開頭和末尾的
空格。

其實去空格可使用正則去匹配的去掉,這裏寫一個去空格函數

/*trim    去掉空白
str要處理的字符串        
[type]     類型:l 去除左邊的空白    r去除右邊空白    b去掉兩邊的空白        a去除全部空白*/
function trim (str,type) {
    var type=type||"b";
    if(type=="b"){
        return str.replace(/^\s*|\s*$/g,"");
    }else if(type=="l"){
        return str.replace(/^\s*/g,"");
    }else if(type=="r"){
        return str.replace(/\s*$/g,"");
    }else if(type=="a"){
        return str.replace(/\s*/g,"");
    }
}

字符串大小寫轉換

toLowerCase()、toLocaleLowerCase()、toUpperCase()和 toLocaleUpperCase()

字符串的模式匹配方法

match()

參數:一個正則表達式或RegExp對象

返回一個數組。在字符串上調用這個方法本質上與調用RegExp的exec()方法相同。

var text = "cat, bat, sat, fat";  
var pattern = /.at/; 
 
//與 pattern.exec(text)相同 
var matches = text.match(pattern);         
alert(matches.index);             //0 
alert(matches[0]);                 //"cat" 
alert(pattern.lastIndex);          //0

search()

參數:一個正則表達式或RegExp對象

返回字符串中第一個匹配項的索引,若是沒有找到,則返回-1

var text = "cat, bat, sat, fat";  
var pos = text.search(/at/); 
alert(pos);   //1

replace()

參數:一個RegExp對象或者一個字符串(這個字符串不會被轉換成正則表達式)一個字符串或一個函數

利用replace()進行替換的時候,若是傳入的是字符串,則只會替換第一個子字符串,要想替換全部的子字符串,則須要傳入一個正則表達式,並且要指定全局(g)標誌

var text = 'cat , bat , sat , fat';
var result = text.replace('at','ond');
console.log(result); // =>'cont , bat , sat , fat'

result = text.replace(/at/g,'ond');
console.log(result); //=>'cont , bont , sont , font'

該方法並不改變調用它的字符串自己,只是返回一個新的替換後的字符串。

當第二個參數爲函數時函數的返回值做爲替換字符串。與第二個參數是字符串同樣,若是第一個參數是正則表達式,而且全局匹配,則這個函數的方法將被屢次調用,每次匹配都會被調用。

該函數的參數:

  • match:匹配的子串

  • p1,p2...:假如replace()方法的第一個參數是RegExp對象,則表明第n個括號匹配的字符串。

  • offset:匹配到的子字符串在原字符串中的偏移量。(好比,若是原字符串是「abcd」,匹配到的子字符串時「bc」,那麼這個參數是1)

  • 被匹配的原字符串

function replacer(match , p1 , p2 , p3 , offset , string){
    // p1 is nondigits, p2 digits, and p3 non-alphanumerics
    console.log(`${match}
                 ${p1}
                 ${p2}
                 ${p3}
                 ${offset}
                 ${string}`); 
    /* => abc12345#$*%
         abc
         12345
         #$*%
         0
         abc12345#$*%"    */         
    console.log([p1, p2, p3].join(' - ')); // => "abc - 12345 - #$*%"
    return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); // =>"abc - 12345 - #$*%"

split()

參數:用於分隔字符串的分隔符數字(可選,用於指定數組的大小)

做用:基於指定的分隔符將一個字符串分割成多個子字符串,並將結果放在一個數組中,分隔符能夠是字符串,也能夠是RegExp對象

var color = 'red,blue,yellow,black';
var color1 = color.split(',');        // =>['red','blue','yellow','black']
var color2 = color.split(',',2);    // =>['red','blue']
var color3 = color.split(/[^\,]+/); // =>["", ",", ",", ",", ""]

最後一個調用split的時候,出現了先後的兩個空白,是由於經過正則表達式指定的分隔符出如今了字符串的開頭和結尾。

localeCompare()

這個方法用於比較兩個字符串,並返回下列值中的一個:

  • 若是字符串在字母表中應該排在字符串參數以前,則返回負數(大多狀況下爲-1)

  • 若是相等,則返回0

  • 若是排在字符串參數以前,則返回正數(大多數狀況下爲1)

fromCharCode()

String構造函數的一個靜態方法

參數:一個或多個字符串編碼

做用:將接收到的一個或多個字符串編碼轉換成一個字符串,這個方法與實例方法charCodeAt()執行相反的操做。

/*fromCharCode*/
String.fromCharCode(104,101,108,108,111);    // =>hello
/*charCodeAt*/
let s = 'hello';
for(let i=0;i<s.length;i++){
  console.log(`${s[i]}----${s[i].charCodeAt()}`);
}
/*
"h----104"
"e----101"
"l----108"
"l----108"
"o----111"
*/

最後寫一個字符串與數組方法應用的一個例子,熟悉它們方法的話很簡單,不熟悉就會以爲有點兒亂。

let s = 'hello';
let news = s.split('').reverse().join('');
console.log(news); // => "olleh"

另附js中String和Array方法的總結圖:

圖片描述

相關文章
相關標籤/搜索