'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
Solution 1:[1]
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>";
Solution 2:[2]
Code : (FIXED)
var new_words = words.replace(/\n/g," ");
Solution 3:[3]
Some simple solution would look like
words.replace(/(\n)/g," ");
Solution 4:[4]
No need for global regex, use replaceAll instead of replace
myString.replaceAll('\n', ' ')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | enriquejr99 |
