简体   繁体   English

如何在JavaScript中使用split函数和RegEx按长度分割字符串?

[英]How to split a string by length using split function and a RegEx in javascript?

I want to split a string that represent a sequence of bits (only "0" and "1") in different strings with a length of 8. 我想用一个长度为8的字符串来拆分一个代表位序列(仅“ 0”和“ 1”)的字符串。

I would like to use the javascript split function, and I know that It is possible to use a regex to achieve that division. 我想使用javascript split函数,并且我知道可以使用正则表达式来实现该划分。 I have something close to a solution: 我有一个解决方案:

"10111001110001011011".split(/([01]{8})/)

But it return an array with five elements, where there are two empty: 但是它返回一个包含五个元素的数组,其中有两个为空:

(5) ["", "10111001", "", "11000101", "1011"]

What should be the right regex to use in split to get one array with only the non empty strings. 什么是正确的正则表达式,可用于拆分以仅包含非空字符串的数组。 (I don´t want to use another function to filter the result...) (我不想使用其他函数来过滤结果...)

As Alexander pointed out at his comment, you need to use .match, like this: 正如Alexander在他的评论中指出的那样,您需要使用.match,如下所示:

 var binaryNumber = "1011100111000101101100110101110111011100010101"; console.log(binaryNumber.match(/.{1,8}/g)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM