我有这个字符串

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

使用JavaScript,最快的方法是什么

var name = "john smith";
var street= "123 Street";
//etc...

当前回答

尽管这不是最简单的方法,但你可以这样做:

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

其他回答

JavaScript:将字符串转换为数组JavaScript拆分

var str = "This-javascript-tutorial-string-split-method-examples-tutsmake." Var result = str.split('-'); console.log(结果); . getelementbyid(“秀”)。innerHTML = result; < html > < >头 <title>你如何分割一个字符串,在javascript中打破一个特定的字符?< /名称> < / >头 <身体> < p id = "显示" > < / p > < /身体> < / html >

https://www.tutsmake.com/javascript-convert-string-to-array-javascript/

用这个代码——

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

}

使用JavaScript的String.prototype.split函数:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.

喜欢的东西:

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

可能是最简单的

这个答案不如破坏性的答案好,但鉴于这个问题是12年前提出的,我决定给出一个12年前也适用的答案。

function Record(s) {
    var keys = ["name", "address", "address2", "city", "state", "zip"], values = s.split("~"), i
    for (i = 0; i<keys.length; i++) {
        this[keys[i]] = values[i]
    }
}

var record = new Record('john smith~123 Street~Apt 4~New York~NY~12345')

record.name // contains john smith
record.address // contains 123 Street
record.address2 // contains Apt 4
record.city // contains New York
record.state // contains NY
record.zip // contains zip