4 回答
TA贡献1784条经验 获得超7个赞
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.
TA贡献1789条经验 获得超10个赞
var s = 'john smith~123 Street~Apt 4~New York~NY~12345';var fields = s.split(/~/);var name = fields[0];var street = fields[1];
TA贡献1942条经验 获得超3个赞
根据ECMAScript 6ES6,干净的方法是破坏数组:
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
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!
添加回答
举报