如何使用split(<regexp>)拆分字符串并获取分隔符?

时间:2018-01-04 01:34:16

标签: javascript arrays regex string split

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

'M 10 10L 150 300'

结果:

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

但我希望收到这个:

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

<小时/> 使用JavaScript获得该结果的最快方法是什么?

1 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
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
)
&#13;
&#13;
&#13;

相关问题