Javascript Split Space Delimited String and Trim Extra Commas and Spaces

后端 未结 6 2365
时光说笑
时光说笑 2021-02-19 15:14

I need to split a keyword string and turn it into a comma delimited string. However, I need to get rid of extra spaces and any commas that the user has already input.



        
相关标签:
6条回答
  • 2021-02-19 15:52

    In addition to Felix Kling's answer

    If you have preceding and trailing white spaces, you should remove those first.

    It's possible to add an "extension method" to a JavaScript String by hooking into it's prototype. I've been using the following to trim preceding and trailing white-spaces, and thus far it's worked a treat:

    // trims the leading and proceeding white-space
    String.prototype.trim = function()
    {
        return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    };
    
    0 讨论(0)
  • 2021-02-19 16:00

    If you just want to split, trim and join keeping the whitespaces, you can do this with lodash:

    // The string to fix
    var stringToFix = "The Wizard of Oz,Casablanca,The Green Mile";
    
    // split, trim and join back without removing all the whitespaces between
    var fixedString = _.map(stringToFix.split(','), _.trim).join(' == ');
    
    // output: "The Wizard of Oz == Casablanca == The Green Mile"
    console.log(fixedString);
    <script src="https://cdn.jsdelivr.net/lodash/4.16.3/lodash.min.js"></script>

    0 讨论(0)
  • 2021-02-19 16:01
    let query = "split me by space and remove trailing spaces and store in an array  ";
    let words = query.trim().split(" ");
    console.log(words)
    

    Output : [ 'split', 'me', 'by', 'space','and','remove', 'trailing', 'spaces', 'and', 'store', 'in', 'an', 'array' ]

    0 讨论(0)
  • 2021-02-19 16:04

    In ES6:

    var temp = str.split(",").map((item)=>item.trim());
    
    0 讨论(0)
  • 2021-02-19 16:09

    You will need a regular expression in both cases. You could split and join the string:

    str = str.split(/[\s,]+/).join();
    

    This splits on and consumes any consecutive white spaces and commas. Similarly, you could just match and replace these characters:

    str = str.replace(/[\s,]+/g, ',');
    

    For the trailing comma, just append one

    str = .... + ',';
    

    If you have preceding and trailing white spaces, you should remove those first.

    Reference: .split, .replace, Regular Expressions

    0 讨论(0)
  • 2021-02-19 16:15

    I would keep it simple, and just match anything not allowed instead to join on:

    str.split(/[^a-zA-Z-]+/g).filter(v=>v);
    

    This matches all the gaps, no matter what non-allowed characters are in between. To get rid of the empty entry at the beginning and end, a simple filter for non-null values will do. See detailed explanation on regex101.

    var str = ", ,, ford,    tempo, with,,, sunroof,, ,";
    
    var result = str.split(/[^a-zA-Z-]+/g).filter(v=>v).join(',');
    
    console.info(result);

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