如何使用split拆分字符串( )并获得分隔符? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

我想使用String.prototype.split(/ [a-zA-Z] /)在每个字母处拆分以下字符串:

'M 10 10L 150 300'

结果:

[ "", " 10 10", " 150 300" ]

但我希望收到这个:

[ "", "M 10 10", "L 150 300" ]


What is the fastest way to get that result using JavaScript?
javascript arrays regex string split
1个回答
1
投票

尝试使用与/[a-zA-Z][^a-zA-Z]*/g的匹配来捕获字母和以下非字母字符:

let s = 'M 10 10L 150 300'

console.log(
  s.match(/^[^a-zA-Z]+|[a-zA-Z][^a-zA-Z]*/g)   // ^[^a-zA-Z]+ to include the case when 
                                               // the string doesn't begin with a letter
)
© www.soinside.com 2019 - 2024. All rights reserved.