找到特定字符时将字符串拆分为2个部分

时间:2018-02-13 20:18:24

标签: javascript string split

我有来自launchlibrary.net的API响应的字符串,如下所示:

"Falcon 9 Full Thrust | PAZ & Microsat-2a, Microsat-2b"

字符串的第一部分是火箭的名称,第二部分是任务的名称。

我想从前一个字符串创建2个新字符串:

let rocketName = first part of the string before Vertical Bar Character -> |
let missionName = second part of the string after Vertical Bar Character -> |

3 个答案:

答案 0 :(得分:3)

使用.split()



var inp = "Falcon 9 Full Thrust | PAZ & Microsat-2a, Microsat-2b";
var result = inp.split(" | ");
var rocketname = result[0];
var missionname = result[1];
console.log(rocketname);




答案 1 :(得分:0)

let str = "foo | bar";
let parts = str.split("|")   // is now an array
let rocketName =  parts[0].trim()
let missionName = parts[1].trim()

答案 2 :(得分:0)

let response = "Falcon 9 Full Thrust | PAZ & Microsat-2a, Microsat-2b";
let result = response.split(" | "); 
//result = ["Falcon 9 Full Thrust", "PAZ & Microsat-2a, Microsat-2b"];
let rocketName = result[0]; //"Falcon 9 Full Thrust"
let missionName = result[1]; //"PAZ & Microsat-2a, Microsat-2b"