How do I split a string, breaking at a particular character?

后端 未结 17 2231
误落风尘
误落风尘 2020-11-21 05:07

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



        
相关标签:
17条回答
  • 2020-11-21 05:19

    According to ECMAScript6 ES6, the clean way is destructuring 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!

    0 讨论(0)
  • 2020-11-21 05:21

    Since the splitting on commas question is duplicated to this question, adding this here.

    If you want to split on a character and also handle extra whitespace that might follow that character, which often happens with commas, you can use replace then split, like this:

    var items = string.replace(/,\s+/, ",").split(',')
    
    0 讨论(0)
  • 2020-11-21 05:24

    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];
    
    0 讨论(0)
  • 2020-11-21 05:24

    Try in Plain Javascript

     //basic url=http://localhost:58227/ExternalApproval.html?Status=1
    
     var ar= [url,statu] = window.location.href.split("=");
    
    0 讨论(0)
  • 2020-11-21 05:30

    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.
    
    0 讨论(0)
  • 2020-11-21 05:32

    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.

    0 讨论(0)
提交回复
热议问题