我有这个字符串
'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...
当前回答
你可以使用split来拆分文本。
作为替代,你也可以使用match,如下所示
var str = 'john smith~123 Street~Apt 4~New York~NY~12345'; 匹配= str.match(/[^~]+/g); console.log(匹配); document . write(匹配);
正则表达式[^~]+将匹配除~之外的所有字符,并在数组中返回匹配的字符。然后可以从中提取匹配项。
其他回答
你不需要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
//basic url=http://localhost:58227/ExternalApproval.html?Status=1
var ar= [url,statu] = window.location.href.split("=");
split()方法用于将字符串转换为数组。 它接受一个可选参数,作为一个字符,对其进行拆分。在你的情况下(~)。
如果splitOn被跳过,它将简单地将string放在数组的第0个位置。
如果splitOn只是一个" ",那么它将转换数组的单个字符。
在你的例子中:
var arr = input.split('~');
将在arr[0]处获取名称,在arr[1]处获取街道。
你可以在这里阅读更详细的解释 在JavaScript中拆分
这个答案不如破坏性的答案好,但鉴于这个问题是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
扎克是对的。使用他的方法,你也可以做出一个看似“多维”的数组。我在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(",");