天天看點

JS:字元串常用方法整理

函數 說明 示例
String.fromCharCode() 傳回Unicode碼對應的字元串 String.fromCharCode('20013'); // "中"
charCodeAt() 傳回字元的Unicode碼 '中'.charCodeAt(); // 20013
charAt() 傳回指定位置的字元 'abc'.charAt(1); // "b"
concat() 連接配接兩個字元串 'ab'.concat('cd'); // "abcd"
slice() 截取字元串(推薦) 'abc'.slice(start, end)
substring() 截取字元串 'abc'.substring(start, end)
substr() 'abc'.substr(from, length)
indexOf() 頭部開始比對,沒有傳回-1 'abc'.indexOf('b'); // 1
lastIndexOf() 尾部開始比對 ,沒有傳回-1 'abc'.lastIndexOf('b'); // 1
trim() 去除空格,傳回一個新字元串,不改變原字元串。 ' abc '.trim(); // "abc"
toLowerCase() 轉小寫 'ABC'.toLowerCase(); // "abc"
toUpperCase() 轉大寫 'abc'.toUpperCase(); // "ABC"
localeCompare() 比較兩個字元串,傳回-1,0,1 'abc'.localeCompare("123"); // 1
match() 比對子串數組,沒有傳回null 'abc'.match('b'); // ['b']
search() 查找子串,沒有傳回-1 'abc'.search('b'); // 1
replace() 替換字元串 'abc'.replace('a', 'd'); // "dbc"
split() 分割字元串為數組 'abc'.split(''); // ["a", "b", "c"]
includes() 是否找到字元串 'abc'.includes('a'); // true
startsWith() 是否在頭部 'abc'.startsWith('a'); // true
endsWith() 是否在尾部 'abc'.endsWith('a'); // false
repeat() 重複原字元串 'abc'.repeat(2); // "abcabc"
padStart() 頭部補全 'abc'.padStart(4, 'x'); // "xabc"
padEnd() 尾部補全 abc'.padEnd(5, 'x'); // "abcxx"

參考

JS String對象的方法總結(ES5 與 ES6)

繼續閱讀