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
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.
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.
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>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With