简体   繁体   中英

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!

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 .

.split() works on strings so that is why you are seeing the error - you are calling it on a string which returns an array, and they trying to call it again on the array. There are many ways to approach this.

I'd be tempted to take a short cut and replace all spaces with semicolons and then perform a single .split(';') to generate the array, and then use .filter() to filter out only those strings in the array that match the length you are looking for.

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