简体   繁体   中英

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.

I would like to use the javascript split function, and I know that It is possible to use a regex to achieve that division. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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