javascript:按组拆分字符串

时间:2019-01-11 18:56:27

标签: javascript regex

是否有标准功能可以做到这一点:

一些例子:

"LLLDDDDLL" -> ["LLL", "DDDD", "LL"]
"LLLDDDD" -> ["LLL", "DDDD"]
"DDDDLL" -> ["DDD", "LL"]

1 个答案:

答案 0 :(得分:1)

通过使用此正则表达式

(\w)\1*

此正则表达式将匹配连续重复的字符。

function splitRepeated( input ) {
  let result = input.match(/(\w)\1*/g) 
  console.log( result )
}

splitRepeated("LLLDDDDLL")
splitRepeated("LLLDDDD")
splitRepeated("DDDDLL")