我有这个字符串
'john smith~123 Street~Apt 4~New York~NY~12345'
使用JavaScript,最快的方法是什么
var name = "john smith";
var street= "123 Street";
//etc...
我有这个字符串
'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
其他回答
因为分隔逗号的问题被复制到这个问题上,所以在这里添加这个。
如果你想对一个字符进行拆分,并处理该字符后面可能出现的额外空格,通常使用逗号,你可以使用替换然后拆分,如下所示:
var items = string.replace(/,\s+/, ",").split(',')
嗯,最简单的方法是:
var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]
根据ECMAScript6 ES6,干净的方法是解构数组:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345'; Const[名称,街道,单位,城市,州,zip] = input.split('~'); console.log(名称);// John Smith console.log(街);// 123街 console.log(单位);// 4号房间 console.log(城市);//纽约 console.log(状态);/ /纽约 console.log (zip);/ / 12345
输入字符串中可能有额外的项。在这种情况下,你可以使用rest操作符获取一个数组,或者直接忽略它们:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345'; Const[名字,街道,…Others] = input.split('~'); console.log(名称);// John Smith console.log(街);// 123街 console.log(他人);// ["Apt 4", "New York", "NY", "12345"]
我假设值是只读引用,并使用了const声明。
党委ES6 !
扎克是对的。使用他的方法,你也可以做出一个看似“多维”的数组。我在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(",");
这个答案不如破坏性的答案好,但鉴于这个问题是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