How do I split a string, breaking at a particular

2018-12-31 00:44发布

I have this string

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

Using JavaScript, what is the fastest way to parse this into

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

11条回答
浮光初槿花落
2楼-- · 2018-12-31 01:22

With JavaScript’s String.prototype.split function:

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.
查看更多
临风纵饮
3楼-- · 2018-12-31 01:22

You can use split to split the text.

As an alternative, you can also use match as follow

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

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

The regex [^~]+ will match all the characters except ~ and return the matches in an array. You can then extract the matches from it.

查看更多
大哥的爱人
4楼-- · 2018-12-31 01:23

Use this code------

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

}
查看更多
有味是清欢
5楼-- · 2018-12-31 01:25

You'll want to look into JavaScript's substr or split as this is not really a task suited for jQuery

查看更多
孤独寂梦人
6楼-- · 2018-12-31 01:34

Even though this is not the simplest way, you could do this:

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"
}

Update for ES2015, using destructuring

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
查看更多
登录 后发表回答