How to remove all line breaks from a string

前端 未结 16 1253
轮回少年
轮回少年 2020-11-22 11:36

I have a text in a textarea and I read it out using the .value attribute.

Now I would like to remove all linebreaks (the character that is produced when you press

相关标签:
16条回答
  • 2020-11-22 12:33
    var str = "bar\r\nbaz\nfoo";
    
    str.replace(/[\r\n]/g, '');
    
    >> "barbazfoo"
    
    0 讨论(0)
  • 2020-11-22 12:33

    On mac, just use \n in regexp to match linebreaks. So the code will be string.replace(/\n/g, ''), ps: the g followed means match all instead of just the first.

    On windows, it will be \r\n.

    0 讨论(0)
  • 2020-11-22 12:36

    The simplest solution would be:

    let str = '\t\n\r this  \n \t   \r  is \r a   \n test \t  \r \n';
    str.replace(/\s+/g, ' ').trim();
    console.log(str); // logs: "this is a test"
    

    .replace() with /\s+/g regexp is changing all groups of white-spaces characters to a single space in the whole string then we .trim() the result to remove all exceeding white-spaces before and after the text.

    Are considered as white-spaces characters:
    [ \f\n\r\t\v​\u00a0\u1680​\u2000​-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

    0 讨论(0)
  • 2020-11-22 12:38

    To remove new line chars use this:

    yourString.replace(/\r?\n?/g, '')
    

    Then you can trim your string to remove leading and trailing spaces:

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