Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To remove space between strings in javascript, just use the replace() method with the /\s/g regex then it will return a new string without spaces.

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If the pattern is a string, only the first occurrence will be replaced.

Let’s take an example to remove space between strings in javascript using the replace() method.

const regex = /\s/g;

var str = "site logo.png";

str.replace(regex, '');
// 👇️ Output
//   "sitelogo.png"

Today, I’m going to show you How do I remove space between strings in javascript, as above mentioned here, I’m going to use the replace() method with the /\s/g regex or split() method with the join().

Let’s start today’s tutorial how do you remove space between strings in javascript?

In this example, we will do

  1. example of remove space between string using replace with regex
  2. example of removing space between strings using split() with join()

Let’s write code…

example of remove space between string using replace with regex

Using replace() and /\s/g we are finding spaces in string and replaceing width empty string.

const regex = /\s/g;

var str = "site logo.png";

str = str.replace(regex, '');
// 👇️ Output
//   "sitelogo.png"

example of remove space between string using split() with join()

  1. Using the split() method, we are making an array of elements based on the number of spaces in the string.
  2. Using the join() method, we are joined the array of elements to a single string.
var str = "site logo.png";

str = str.split(' ').join('');
// 👇️ Output
//   "sitelogo.png"

I hope it helps you, All the best đź‘Ť.