我有这个字符串
'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 divided = str.split("/~/");
var name=divided[0];
var street = divided[1];
可能是最简单的
其他回答
扎克是对的。使用他的方法,你也可以做出一个看似“多维”的数组。我在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(",");
你可以使用split来拆分文本。
作为替代,你也可以使用match,如下所示
var str = 'john smith~123 Street~Apt 4~New York~NY~12345'; 匹配= str.match(/[^~]+/g); console.log(匹配); document . write(匹配);
正则表达式[^~]+将匹配除~之外的所有字符,并在数组中返回匹配的字符。然后可以从中提取匹配项。
喜欢的东西:
var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];
可能是最简单的
使用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[名称,街道,单位,城市,州,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 !