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:10

well, easiest way would be something like:

var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]
查看更多
与风俱净
3楼-- · 2018-12-31 01:10

If Spliter is found then only

Split it

else return the same string

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];
        }
    }
}
查看更多
妖精总统
4楼-- · 2018-12-31 01:11

You don't need 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];
查看更多
听够珍惜
5楼-- · 2018-12-31 01:11

Something like:

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

Is probably going to be easiest

查看更多
弹指情弦暗扣
6楼-- · 2018-12-31 01:12

According to ECMAScript6 ES6, the clean way is destructing arrays:

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

You may have extra items in the input string. In this case, you can use rest operator to get an array for the rest or just ignore them:

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

I supposed a read-only reference for values and used the const declaration.

Enjoy ES6!

查看更多
刘海飞了
7楼-- · 2018-12-31 01:13

Zach had this one right.. using his method you could also make a seemingly "multi-dimensional" array.. I created a quick example at 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(",");
查看更多
登录 后发表回答