我有这个字符串

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

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

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

当前回答

尽管这不是最简单的方法,但你可以这样做:

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

其他回答

嗯,最简单的方法是:

var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]

因为分隔逗号的问题被复制到这个问题上,所以在这里添加这个。

如果你想对一个字符进行拆分,并处理该字符后面可能出现的额外空格,通常使用逗号,你可以使用替换然后拆分,如下所示:

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

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/

这string.split(“~”)[0];把事情做好。

来源:String.prototype.split ()


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

首先是分裂函数。我们想把这个“john smith~123 Street~ 4 Apt ~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"]

要获取第一个元素,可以使用列表操作符[0]。让我们构建第一个函数:

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

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

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

现在用它来组合splitByTilde和first函数。

const getName = compose(first, splitByTilde);

let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
getName(string); // "john smith"

尝试使用纯Javascript

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

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