How to remove all line breaks from a string

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

提交回复
热议问题