我有这个字符串
'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...
当前回答
扎克是对的。使用他的方法,你也可以做出一个看似“多维”的数组。我在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(",");
其他回答
如果分裂者被发现,那么只有
它会分裂
否则返回相同的字符串
函数 SplitTheString(ResultStr) { if (ResultStr != null) { var splitchars = '~'; if (ResultStr.indexOf(SplitChars) >= 0) { var DtlStr = ResultStr.split(SplitChars); var name = DtlStr[0]; var street = DtlStr[1]; } } }
你不需要jQuery。
var s = 'john smith~123 Street~Apt 4~New York~NY~12345'; Var字段= s.split(/~/); 变量名称=字段[0]; Var street = fields[1]; console.log(名称); console.log(街);
您需要研究JavaScript的substr或split,因为这不是一个真正适合jQuery的任务。
扎克是对的。使用他的方法,你也可以做出一个看似“多维”的数组。我在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(",");
尽管这不是最简单的方法,但你可以这样做:
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