javascript replace all spaces – How to replace all spaces in a string?

javascript replace all spaces Use the JavaScript replace() method. You can simply use the js replace() to replace the multiple spaces inside a string.

javascript replace all spaces

The \s meta character in js regular expressions matches any whitespace character: spaces, tabs, newlines and Unicode spaces.

If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() only the first occurence.

How to replace white space inside a string in JavaScript?
Exmaple 1:

const member_comments = 'Hi my website is Pakainfo'
member_comments.replace(/\s/g, '') //HimywebsiteisPakainfo

Example : 2

const member_comments = 'Hi my website is Pakainfo'
const nameCleaned = member_comments.replace(/\s/g, '')

Pure Javascript : replace all spaces

var result = member_comments.split(" ").join("");

Replace all spaces in a string with ‘+’

var member_comments = 'j d k';
var replaced = member_comments.split(' ').join('+');

Don’t Miss : Remove white space JavaScript

Read Also:  javascript wait 1 second(Delay, Sleep, Pause, & Wait)

How to replace all spaces in a string?

Example 1:

var result = member_comments.replace(/ /g, ";");

How to Replace All Spaces in Javascript?

Demo

var member_comments = "This string is kind of spacey.";
member_comments = member_comments.replace(" ", "_");

console.log(member_comments);

//OR

var i = 0, strLength = member_comments.length;
for(i; i < strLength; i++) {
 member_comments = member_comments.replace(" ", "_");
}
console.log(member_comments);

function findAndReplace(member_comments, target, replacement) {
 var i = 0, length = member_comments.length;
 for (i; i < length; i++) {
   member_comments = member_comments.replace(target, replacement);
 }
 return member_comments;
}
console.log(findAndReplace(member_comments, " ", "_"));
console.log(findAndReplace("No... not me too!", " ", "_")); 

bonus

var member_comments = "Sorry, Not RegEx! Please no!";
member_comments = member_comments.replace(/\s/g, "_");
console.log(member_comments); //"Not_RegEx!_Please_no!"

I hope you get an idea about javascript replace all spaces.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.