简体   繁体   English

将字符串拆分为多个输出字符串

[英]split string into multiple output string

I'm having string like this 我有这样的字符串

String input = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00"

I have tried lot of options by google-ing like indexOf() over load etc but could not get the exact result. 我已经尝试通过谷歌搜索很多选项,例如在加载等indexOf(),但无法获得确切的结果。

Is that possible I could have multiple output string on the basis of "|" 是否可以在“ |”的基础上使用多个输出字符串?

Expected output 预期产量

String one = input.substring(0,input.indexOf("|")) = ABCD
String two = opt/kelly/box.txt
String three = DXC
String four = 20-12-2015 11:00:00

How can I do for the remaining ones ? 剩下的我该怎么办?

Any suggestion please how can I get this result using indexOf with substring. 任何建议,请问如何使用带有子字符串的indexOf来获得此结果。

Thanks in Advance !! 提前致谢 !!

It's easy. 这很容易。 All you need to do is to use .split : 您需要做的就是使用.split

 var input = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00"; input = input.split("|"); console.log(input); 

But if you need them in variables like one , two , etc., you might need to use destructuring assignment . 但是,如果你需要他们的变量,如onetwo ,等等,你可能需要使用解构赋值 You don't need to use .indexOf here. 您无需在此使用.indexOf

Using Destructuring assignment 使用解构分配

 var input = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00"; var [one, two, three, four] = input.split("|"); console.log(one); console.log(two); console.log(three); console.log(four); 

First, be aware that JavaScript doesn't allow you to declare your data type as you are doing with: 首先,请注意,JavaScript不允许您像声明那样声明数据类型:

 String input ....

You can only declare the variable (ie var input ... ) 您只能声明变量(即var input ...

Barring that, the .split() method (which splits a string based on your delimiter and returns an array of the parts to you) will do it. 除非使用.split()方法(该方法根据您的定界符分割字符串并向您返回部分数组)即可。

Also, if you need to store each array element in its own variable, you can use a destructuring assignment to accomplish that. 同样,如果需要将每个数组元素存储在其自己的变量中,则可以使用解构分配来完成此操作。

 // Here's your scenario: var input = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00"; var one = input.substring(0,input.indexOf("|")) // ABCD // Do the remaining split on the original string without the already found parts var [two, three, four] = input.replace(one + "|","").split("|"); console.log(one); console.log(two); console.log(three); console.log(four); // Here'e a cleaner alternative that uses a destructuring assignment: var input2 = "ABCD|opt/kelly/box.txt|DXC|20-12-2015 11:00:00"; var [one2, two2, three2, four2] = input.split("|"); console.log(one2); console.log(two2); console.log(three2); console.log(four2); 

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

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