How can I replace newlines/line breaks with spaces in javascript?
JavascriptRegexJavascript Problem Overview
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
Javascript Solutions
Solution 1 - 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/
Solution 2 - Javascript
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 3 - Javascript
Code : (FIXED)
var new_words = words.replace(/\n/g," ");
Solution 4 - Javascript
Some simple solution would look like
words.replace(/(\n)/g," ");
Solution 5 - Javascript
No need for global regex, use replaceAll
instead of replace
myString.replaceAll('\n', ' ')