我有这个字符串

'john smith~123 Street~Apt 4~New York~NY~12345'

使用JavaScript,最快的方法是什么

var name = "john smith";
var street= "123 Street";
//etc...

当前回答

你不需要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(街);

其他回答

你不需要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(街);

喜欢的东西:

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(",");

如果分裂者被发现,那么只有

它会分裂

否则返回相同的字符串

函数 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]; } } }

JavaScript:将字符串转换为数组JavaScript拆分

var str = "This-javascript-tutorial-string-split-method-examples-tutsmake." Var result = str.split('-'); console.log(结果); . getelementbyid(“秀”)。innerHTML = result; < html > < >头 <title>你如何分割一个字符串,在javascript中打破一个特定的字符?< /名称> < / >头 <身体> < p id = "显示" > < / p > < /身体> < / html >

https://www.tutsmake.com/javascript-convert-string-to-array-javascript/