Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a var that contains a big list of words (millions) in this format:

var words =  " car house home computer go  went "; 

I want to make a function that will replace the newline between each word with space.

So the results would something look like this:

car house home computer go went 
like image 660
user1200640 Avatar asked Mar 24 '12 06:03

user1200640


People also ask

How do you remove line breaks from a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

How do you replace a space in JavaScript?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.


2 Answers

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/

like image 172
jfriend00 Avatar answered Sep 25 '22 15:09

jfriend00


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>";
like image 20
Wiktor Stribiżew Avatar answered Sep 24 '22 15:09

Wiktor Stribiżew