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

时间:2016-12-12 20:58:06

标签: javascript

我有这样的字符串

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

我已经通过google-ing像indexOf()过载等尝试了很多选项,但无法得到确切的结果。

这是否可能我可以在“|”

的基础上拥有多个输出字符串

预期输出

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

我该如何处理其余的?

如有任何建议,请问如何使用indexOf和substring来获得此结果。

先谢谢!!

2 个答案:

答案 0 :(得分:4)

这很容易。您需要做的就是使用.split

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

但如果您需要onetwo等变量,则可能需要使用destructuring assignment。您无需在此处使用.indexOf

使用解构分配

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);

答案 1 :(得分:1)

首先,请注意JavaScript不允许您像以前一样声明数据类型:

 String input ....

您只能声明变量(即var input ...

除此之外, .split() 方法(根据您的分隔符拆分字符串并将部分数组返回给您)将会这样做。

此外,如果您需要将每个数组元素存储在自己的变量中,则可以使用 destructuring assignment 来完成此操作。

// 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);

相关问题