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