Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  102] [ 3]  / answers: 1 / hits: 135396  / 12 Years ago, sat, march 24, 2012, 12:00:00

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

More From » regex

 Answers
34

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.


Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.




let words = anbncndne;
console.log(Before:);
console.log(words);
words = words.replace(/n/g, );

console.log(After:);
console.log(words);




[#86633] Thursday, March 22, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yvettel

Total Points: 517
Total Questions: 101
Total Answers: 102

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
;