我有这个字符串
'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...
使用 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.
根据 ECMAScript6 ES6
,干净的方法是解构数组:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
const [name, street, unit, city, state, zip] = input.split('~');
console.log(name); // john smith
console.log(street); // 123 Street
console.log(unit); // Apt 4
console.log(city); // New York
console.log(state); // NY
console.log(zip); // 12345
输入字符串中可能有额外的项目。在这种情况下,您可以使用 rest 运算符来获取其余的数组或忽略它们:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
const [name, street, ...others] = input.split('~');
console.log(name); // john smith
console.log(street); // 123 Street
console.log(others); // ["Apt 4", "New York", "NY", "12345"]
我假设值的只读引用并使用了const
声明。
享受 ES6!
你不需要jQuery。
var s = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = s.split(/~/);
var name = fields[0];
var street = fields[1];
即使这不是最简单的方法,您也可以这样做:
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