JavaScript中split()方法用來將字符串分割成子字符串,要截取字符串可以使用substr()方法和substring()方法:1、string.substr(start, length),用于從字符串中截取指定長度的子串;2、string.substring(start, end),string是要截取的字符串,start和end都是基于0的索引。
在JavaScript中,split()方法也是用來將字符串分割成子字符串,并返回一個(gè)由子字符串組成的數(shù)組。如果你需要截取字符串的一部分,可以使用JavaScript字符串的substr()或substring()方法。
substr()方法用于從字符串中截取指定長度的子串,其語法如下:
string.substr(start,?length)
登錄后復(fù)制
其中,string是要截取的字符串,start是起始位置,表示從哪個(gè)位置開始截取子串,length是可選參數(shù),表示要截取的子串長度。
下面是一些示例:
const?text?=?"Hello,?world!"; //?截取"Hello"子串 const?part1?=?text.substr(0,?5);??//?從索引0開始,截取5個(gè)字符 console.log(part1);??//?輸出:?'Hello' //?截取"world!"子串 const?part2?=?text.substr(7);??//?從索引7開始,截取到字符串末尾 console.log(part2);??//?輸出:?'world!' //?截取"ello"子串 const?part3?=?text.substr(1,?4);??//?從索引1開始,截取4個(gè)字符 console.log(part3);??//?輸出:?'ello'
登錄后復(fù)制
另外,substring()方法也可以用于截取字符串的一部分,其語法如下:
string.substring(start,?end)
登錄后復(fù)制
其中,string是要截取的字符串,start和end都是基于0的索引,表示要截取的子串的起始位置和結(jié)束位置(不包括結(jié)束位置本身)。
下面是一些示例:
const?text?=?"Hello,?world!"; //?截取"Hello"子串 const?part1?=?text.substring(0,?5);??//?從索引0開始,直到索引4(不包括5) console.log(part1);??//?輸出:?'Hello' //?截取"world!"子串 const?part2?=?text.substring(7);??//?從索引7開始,直到字符串末尾 console.log(part2);??//?輸出:?'world!' //?截取"ello"子串 const?part3?=?text.substring(1,?5);??//?從索引1開始,直到索引4(不包括5) console.log(part3);??//?輸出:?'ello'
登錄后復(fù)制
需要注意的是,substr()方法和substring()方法在參數(shù)上有所不同,使用時(shí)需要根據(jù)具體情況選擇合適的方法。