如何拆分一个字符串,在特定字符处断开?

633

我有这个字符串

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

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

var name = "john smith";
var street= "123 Street";
//etc...
17个回答

2

尝试使用纯JavaScript

最初的回答
 //basic url=http://localhost:58227/ExternalApproval.html?Status=1

 var ar= [url,statu] = window.location.href.split("=");

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

2

JavaScript: 将字符串转换为数组 JavaScript Split

将字符串分割成子字符串,并将这些子字符串存储在一个数组中。该方法接受一个参数,用于指定分隔符。

原始回答:Split() 方法将字符串分割成数组,返回新数组。该方法不会改变原始字符串。

    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/


2

string.split("~")[0];会让事情变得简单。

来源:String.prototype.split()


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

首先是split函数。我们想将"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函数。使用reduce构建一个compose函数:

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"

1

由于逗号分割问题已经在这个问题中重复出现,所以将其添加到此处。

如果您想要在一个字符上进行分割,并处理可能跟随该字符的额外空格(通常发生在逗号上),您可以使用replace然后split,像这样:

var items = string.replace(/,\s+/, ",").split(',')

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

-2
请使用这段代码——
function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接