我如何分割字符串,在特定字符处断开?

JavaScript

古一Mandy

2020-03-12

我有这串

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

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

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

第1113篇《我如何分割字符串,在特定字符处断开?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
番长樱梅 2020.03.12

使用此代码-

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

}
ㄏ囧囧ㄟ 2020.03.12

尝试使用纯Javascript

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

 var ar= [url,statu] = window.location.href.split("=");
小小Near阳光 2020.03.12

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(",");
小卤蛋猴子猪猪 2020.03.12

就像是:

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

可能是最简单的

JinJin猪猪 2020.03.12

即使这不是最简单的方法,也可以执行以下操作:

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
蛋蛋斯丁 2020.03.12

您将要研究JavaScript的substrsplit,因为这并不是真正适合jQuery的任务。

LEYEvaL 2020.03.12

好吧,最简单的方法是:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android