How to remove all whitespaces and line breaks in js ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

How to remove all whitespaces and line breaks in js ?

So i wanted to know if there's something to like remove all whitespaces and line breaks Example user says ______ P o s si b le ______ It will reply Possible

23rd Mar 2021, 7:10 PM
Abdelrhman Ahmed
Abdelrhman Ahmed - avatar
5 Answers
+ 3
all consecutive 3 or 4 whitespaces (including newlines) are as simple... use regex /\s{3,4}/g only first occurence by removing the 'g' at the end of regex... simplest way to remove n occurrences of whitespaces is to loop without g flag: for (let i=0; i<n; ++i) { str = str.replace(/\s/,""); } by appending '+' after '\s' you target any number of consecutives whitespaces at once. by appending '{a,b}' you target from a to b consecutives whitespaces (a and b must be int and a must be lower than b) only '{a}' target exactly a consecutive whitespaces...
23rd Mar 2021, 7:50 PM
visph
visph - avatar
+ 3
var str = "P o s si\nb le"'; console.log(str.replace(/\s+/g,'""));
23rd Mar 2021, 7:13 PM
visph
visph - avatar
+ 2
For instance the regex /\s/g removes all white space characters https://code.sololearn.com/c2NNbhn6yL51/?ref=app
23rd Mar 2021, 7:18 PM
John Doe
23rd Mar 2021, 7:14 PM
John Doe
0
Oh thx John Doe and visph :D So some questions, is there something like '.trim()' but removes everything except 1st index ? Also is there a way to limit this to remove only 3 or 4 white spaces ? .-.
23rd Mar 2021, 7:39 PM
Abdelrhman Ahmed
Abdelrhman Ahmed - avatar