How to remove all line breaks from a string

前端 未结 16 1254
轮回少年
轮回少年 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:18

    I am adding my answer, it is just an addon to the above, as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:

    var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');
    
    0 讨论(0)
  • 2020-11-22 12:19

    You can use \n in a regex for newlines, and \r for carriage returns.

    var str2 = str.replace(/\n|\r/g, "");
    

    Different operating systems use different line endings, with varying mixtures of \n and \r. This regex will replace them all.

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

    A linebreak in regex is \n, so your script would be

    var test = 'this\nis\na\ntest\nwith\newlines';
    console.log(test.replace(/\n/g, ' '));
    
    0 讨论(0)
  • 2020-11-22 12:22

    Try the following code. It works on all platforms.

    var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
    var break_for_linux = 'test\nwith\nline\nbreaks';
    var break_for_older_mac = 'test\rwith\rline\rbreaks';
    
    break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
    //output
    'test with line breaks'
    
    break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
    //output
    'test with line breaks'
    
    break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
    // Output
    'test with line breaks'
    
    0 讨论(0)
  • 2020-11-22 12:29

    var str = " \n this is a string \n \n \n"
    
    console.log(str);
    console.log(str.trim());

    String.trim() removes whitespace from the beginning and end of strings... including newlines.

    const myString = "   \n \n\n Hey! \n I'm a string!!!         \n\n";
    const trimmedString = myString.trim();
    
    console.log(trimmedString);
    // outputs: "Hey! \n I'm a string!!!"
    

    Here's an example fiddle: http://jsfiddle.net/BLs8u/

    NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.

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

    If you want to remove all control characters, including CR and LF, you can use this:

    myString.replace(/[^\x20-\x7E]/gmi, "")
    

    It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space 0x20-0x7E. Feel free to modify the HEX range as needed.

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