Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to array select only elements with a length of 6

Lets suppose i have this string:

 01234  ; 0123;0424 09234

How can i split these string by two arguments ' ' and ';',

Trim the single elements

and next, select only these elements of the array who have a length of 5

So that at the end it returns this array:

["01234","09234"]

My biggest problem with this task is that i dont know how i should split the string because always when i do:

 a = "0123 9809; 04323 ";
 b = a.split(' ').split(';')

I get this error:

TypeError: Object [object Array] has no method 'split'

Thanks for your help!

like image 957
John Smith Avatar asked Mar 20 '26 22:03

John Smith


1 Answers

Use:

' 01234  ; 0123;0424 09234'.split(/\s|;/).filter(function (e) {
  return e.trim().length === 5;
});

in the example above split accepts a regular expression used for splitting the string. After that we use the high-order function filter, which filters the input.

The is valid for all modern browsers.

like image 67
Minko Gechev Avatar answered Mar 23 '26 10:03

Minko Gechev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!