2

js分割字符串的方法

 1 year ago
source link: https://blog.p2hp.com/archives/9655
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

js分割字符串的方法

适用的各个场景不一样

const arr=['1-2','1-3','2-3','3-4'];

1、string.split()

有特殊字符分割

'1-2'.split('-')
//  ['1', '2']

2、String.substring(start,stop)

start必需。一个非负的整数,规定要提取的子串的第一个字符在 string中的位置。
stop可选,一个非负的整数,包头不包尾,需比最后一个目标字符数加1。

'hello'.substring(1,3)
// 'el'

3、使用String.substr(start,lenght)分割字符串

start 必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。

length 可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 string的开始位置到结尾的字串。

'hello'.substr(1,3)
// 'ell'

4、使用String.slice(start,end)分割字符串

提取字符串的某个部分,并以新的字符串返回被提取的部分。

'hello'.slice(1,3)
// 'el'




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK