How can I replace newlines/line breaks with spaces in javascript?

You can use the .replace() function:

words = words.replace(/\n/g, " ");

Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one.

Working demo: http://jsfiddle.net/jfriend00/VrAw2/


In case there are multiple line breaks (newline symbols) and if there can be both \r or \n, and you need to replace all subsequent linebreaks with one space, use

var new_words = words.replace(/[\r\n]+/g," ");

See regex demo

To match all Unicode line break characters and replace/remove them, add \x0B\x0C\u0085\u2028\u2029 to the above regex:

/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g

The /[\r\n\x0B\x0C\u0085\u2028\u2029]+/g means:

  • [ - start of a positive character class matching any single char defined inside it:
    • \r - (\x0D) - \n] - a carriage return (CR)
    • \n - (\x0A) - a line feed character (LF)
    • \x0B - a line tabulation (LT)
    • \x0C - form feed (FF)
    • \u0085 - next line (NEL)
    • \u2028 - line separator (LS)
    • \u2029 - paragraph separator (PS)
  • ] - end of the character class
  • + - a quantifier that makes the regex engine match the previous atom (the character class here) one or more times (consecutive linebreaks are matched)
  • /g - find and replace all occurrences in the provided string.

var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";

Code : (FIXED)

var new_words = words.replace(/\n/g," ");

Some simple solution would look like

words.replace(/(\n)/g," ");