我如何分割字符串,在特定字符处断开?

我有这串

'john smith~123 Street~Apt 4~New York~NY~12345'

使用JavaScript,将其解析为最快的方法是

var name = "john smith";
var street= "123 Street";
//etc...
番长樱梅2020/03/12 16:11:51

使用此代码-

function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");

}
ㄏ囧囧ㄟ2020/03/12 16:11:51

尝试使用纯Javascript

 //basic url=http://localhost:58227/ExternalApproval.html?Status=1

 var ar= [url,statu] = window.location.href.split("=");
小小Near阳光2020/03/12 16:11:51

Zach拥有这一权利..使用他的方法,您还可以制作一个看似“多维”的数组。.我在JSFiddle http://jsfiddle.net/LcnvJ/2/创建了一个快速示例

// array[0][0] will produce brian
// array[0][1] will produce james

// array[1][0] will produce kevin
// array[1][1] will produce haley

var array = [];
    array[0] = "brian,james,doug".split(",");
    array[1] = "kevin,haley,steph".split(",");
小卤蛋猴子猪猪2020/03/12 16:11:51

就像是:

var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];

可能是最简单的

JinJin猪猪2020/03/12 16:11:51

即使这不是最简单的方法,也可以执行以下操作:

var addressString = "~john smith~123 Street~Apt 4~New York~NY~12345~",
    keys = "name address1 address2 city state zipcode".split(" "),
    address = {};

// clean up the string with the first replace
// "abuse" the second replace to map the keys to the matches
addressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){
    address[ keys.unshift() ] = match;
});

// address will contain the mapped result
address = {
    address1: "123 Street"
    address2: "Apt 4"
    city: "New York"
    name: "john smith"
    state: "NY"
    zipcode: "12345"
}

使用解构的ES2015更新

const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);

// The variables defined above now contain the appropriate information:

console.log(address1, address2, city, name, state, zipcode);
// -> john smith 123 Street Apt 4 New York NY 12345
蛋蛋斯丁2020/03/12 16:11:51

您将要研究JavaScript的substrsplit,因为这并不是真正适合jQuery的任务。

LEYEvaL2020/03/12 16:11:51

好吧,最简单的方法是:

var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]