js和es6中常用的字符串方法總結(收藏)
來源:懂視網
責編:小采
時間:2020-11-27 19:33:09
js和es6中常用的字符串方法總結(收藏)
js和es6中常用的字符串方法總結(收藏):js和es6中常用的字符串,例:slice(start,end) -> 截取字符串,用法:slice的用法和substring的用法基本一樣,只是區別在于:1.slice(start,end) -> start是不能大于end的,否則返回空字符串;2.slice可以接受參數是負數,如果是負數的話,規則
導讀js和es6中常用的字符串方法總結(收藏):js和es6中常用的字符串,例:slice(start,end) -> 截取字符串,用法:slice的用法和substring的用法基本一樣,只是區別在于:1.slice(start,end) -> start是不能大于end的,否則返回空字符串;2.slice可以接受參數是負數,如果是負數的話,規則

let str = 'Hello world';
let use1 = str.substring(0, 3);
console.log(use1); // Hel
let use2 = str.substring(3,0);
console.log(use2); // hel
let use3 = str.substring(2);
console.log(use3); // llo world
2.slice(start,end) -> 截取字符串
用法:
slice的用法和substring的用法基本一樣,只是區別在于:
1.slice(start,end) -> start是不能大于end的,否則返回空字符串;
2.slice可以接受參數是負數,如果是負數的話,規則將按照:字符串的長度和賦值相加,替換掉這個值。舉例如下:
let str = 'abcdefg' // length = 7
str.slice(1,-4) // bc -> str.slice(1,7-4) -> str.slice(1,3)
3.substr(start,length) -> 截取指定位置和指定長度的字符串
用法:
1.substr(start,length) -> 截取的字符串區間為:[start,start+length)->從start開始,算上start數length個字符串;
2.substr(start) -> 截取的字符串區間為:[start,最后一個字符]
let str = 'Hello world';
console.log(str.substr(1,2)) // el
console.log(str.substr(3)) // lo world
4.split()
5.indexOf(char,index) 和 lastIndexOf(char,index)
1.char:是你要找的那個字符,index:是從哪個字符的位置序號開始找(沒有則在indexOf中是最左邊的字符,在lastIndexOf中是最右邊的字符);
2.indexOf是從左往右搜索,而lastIndexOf是從右往左搜索;
3.它們的返回值都是搜到char所在的位置序號,如果沒搜到,返回-1
let str = 'good';
console.log(str.indexOf('o')); // 1
console.log(str.lastIndexOf('o')); // 2
6.charAt(index) 和 charCodeAt(index) 和at(index) (es6屬性)
charAt(index)返回index位置的字符,charCodeAt(index)返回index位置的字符Unicode碼
charAt(index)不能識別大于0xFFFF的字符,這時候可以用at()來識別
var str = 'abc'
str.charAt(0) // a
str.charCodeAt(0) // 97
相關文章:
ES6的字符串模板詳解
分析ES6中多行字符串與連接字符串的表示方法與相關操作技巧
相關視頻:
Javascript - ES6實戰視頻課程-免費在線視頻教程
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
js和es6中常用的字符串方法總結(收藏)
js和es6中常用的字符串方法總結(收藏):js和es6中常用的字符串,例:slice(start,end) -> 截取字符串,用法:slice的用法和substring的用法基本一樣,只是區別在于:1.slice(start,end) -> start是不能大于end的,否則返回空字符串;2.slice可以接受參數是負數,如果是負數的話,規則