//Remove spaces along with tab spaces, new lines
const input_str = "Have you seen spaces here.";
const result_str = input_str.replace(/\s\s+/g, ' ');
console.log(result_str);
// -> Have you seen spaces here.
Here, we have a string variable named input_str that contains words with more than one space between them. We want to remove those spaces with a single space between each word. We are using regex code for that and it will replace all the spaces, new lines, and tabs with a single space.
If you do not want your code to replace tabs or new lines with space, you can use the below code.
const input_str = "This string contains multiple spaces";
const result_str = string = input_str.replace(/ +/g, ' ');
console.log(result_str);
// -> This string contains multiple spaces
const input = " Success is a journey not a destination ";
result = input.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
console.log(result);
// -> Success is a journey not a destination
0 Comments