602

我有这个字符串

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

使用 JavaScript,将其解析为的最快方法是什么

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

17 回答 17

947

使用 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.
于 2008-09-18T20:17:59.233 回答
79

根据 ECMAScript6 ES6,干净的方法是解构数组:

const input = 'john smith~123 Street~Apt 4~New York~NY~12345';

const [name, street, unit, city, state, zip] = input.split('~');

console.log(name); // john smith
console.log(street); // 123 Street
console.log(unit); // Apt 4
console.log(city); // New York
console.log(state); // NY
console.log(zip); // 12345

您可能在输入字符串中有额外的项目。在这种情况下,您可以使用 rest 运算符获取其余的数组或忽略它们:

const input = 'john smith~123 Street~Apt 4~New York~NY~12345';

const [name, street, ...others] = input.split('~');

console.log(name); // john smith
console.log(street); // 123 Street
console.log(others); // ["Apt 4", "New York", "NY", "12345"]

我假设值的只读引用并使用了const声明。

享受 ES6!

于 2017-02-12T09:15:21.023 回答
54

你不需要 jQuery。

var s = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = s.split(/~/);
var name = fields[0];
var street = fields[1];
于 2008-09-18T20:19:29.760 回答
18

即使这不是最简单的方法,您也可以这样做:

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
于 2012-08-14T11:15:30.510 回答
14

您需要查看 JavaScript 的substrsplit,因为这不是真正适合 jQuery 的任务。

于 2008-09-18T20:18:35.240 回答
7

如果找到拆分器,那么只有

它会拆分它

否则返回相同的字符串

function 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];
        }
    }
}
于 2012-11-29T09:45:34.880 回答
6

好吧,最简单的方法是:

var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]
于 2008-09-18T20:20:04.487 回答
5

您可以使用split拆分文本。

作为替代方案,您也可以使用match如下

var str = 'john smith~123 Street~Apt 4~New York~NY~12345';
matches = str.match(/[^~]+/g);

console.log(matches);
document.write(matches);

正则表达式将匹配除数组之外的[^~]+所有字符并返回匹配项。~然后,您可以从中提取匹配项。

于 2015-10-03T10:01:51.010 回答
3

就像是:

var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];

可能是最简单的

于 2008-09-18T20:21:27.697 回答
3

split()JavaScript 中的方法用于将字符串转换为数组。它需要一个可选参数,作为一个字符,在其上进行拆分。在你的情况下(〜)。

如果 splitOn 被跳过,它将简单地将字符串放在数组的第 0 位。

如果 splitOn 只是一个“”,那么它将转换单个字符的数组。

所以在你的情况下:

var arr = input.split('~');

将获得名称arr[0]和街道arr[1]

您可以在 JavaScript中的 Split on 中阅读更详细的说明

于 2020-09-05T13:51:49.917 回答
2

Zach 是对的。使用他的方法,您还可以制作一个看似“多维”的数组。我在 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(",");
于 2013-10-26T18:03:34.513 回答
2

这样string.split("~")[0];事情就搞定了。

来源:String.prototype.split()


另一种使用 curry 和函数组合的函数方法。

所以第一件事就是拆分功能。我们想把它"john smith~123 Street~Apt 4~New York~NY~12345"变成这个["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

const split = (separator) => (text) => text.split(separator);
const splitByTilde = split('~');

所以现在我们可以使用我们专门的splitByTilde功能了。例子:

splitByTilde("john smith~123 Street~Apt 4~New York~NY~12345") // ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

要获取第一个元素,我们可以使用list[0]运算符。让我们构建一个first函数:

const first = (list) => list[0];

算法是:用冒号分割,然后得到给定列表的第一个元素。所以我们可以组合这些函数来构建我们的最终getName函数。构建一个compose函数reduce

const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);

现在用它来组合splitByTildefirst运行。

const getName = compose(first, splitByTilde);

let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
getName(string); // "john smith"
于 2019-01-17T02:13:58.490 回答
2

尝试使用纯 Javascript

 //basic url=http://localhost:58227/ExternalApproval.html?Status=1

 var ar= [url,statu] = window.location.href.split("=");
于 2019-04-09T09:25:28.953 回答
2

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

    var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."
 
    var result = str.split('-'); 
     
    console.log(result);
     
    document.getElementById("show").innerHTML = result; 
<html>
<head>
<title>How do you split a string, breaking at a particular character in javascript?</title>
</head>
<body>
 
<p id="show"></p> 
 
</body>
</html>

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

于 2019-08-28T13:00:48.607 回答
1

由于逗号问题的拆分与此问题重复,因此在此处添加。

如果您想在一个字符上拆分并处理可能跟在该字符后面的额外空格,这通常与逗号一起发生,您可以使用replacethen split,如下所示:

var items = string.replace(/,\s+/, ",").split(',')
于 2019-03-28T13:58:50.667 回答
0

这不如解构答案好,但是看到这个问题是 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
于 2020-11-15T14:58:43.317 回答
-2

使用此代码 -

function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");

}
于 2018-03-01T11:27:31.907 回答