简体   繁体   English

String to array只选择长度为6的元素

[英]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 接下来,只选择长度为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. 在上面的示例中, split接受用于拆分字符串的正则表达式。 After that we use the high-order function filter , which filters the input. 之后我们使用高阶函数 filter来过滤输入。

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. .split()对字符串起作用,这就是你看到错误的原因 - 你在一个返回一个数组的字符串上调用它,并且他们试图在数组上再次调用它。 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. 我很想做一个捷径,用分号替换所有空格,然后执行单个.split(';')来生成数组,然后使用.filter()过滤掉数组中那些字符串匹配您正在寻找的长度。

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

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