Remove All Whitespace From a String in JavaScript Tutorial

Share this Article
Reading Time: 4 minutes
361 Views

Inside this article we will see the concept i.e Remove All Whitespace From a String in JavaScript Tutorial. Article contains the classified information about removing all spaces from a string value using JavaScript.

If you are looking for a solution i.e How to remove spaces from a string using JavaScript then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.

In Javascript there are several different methods available by which you can remove whitespaces from string value. We will see those methods in this tutorial.

Learn More –

Let’s get started.

Example #1: Remove Whitespaces Using ‘replace’ & regex

Here,

We will use the concept of Javascript i.e Remove All Whitespace From a String.

const str = ' h   e   l    l  o ';

const noWhitespace = str.replace(/\s/g, '');

console.log(noWhitespace); // 'hello'

Console Output

Example #2: Remove Whitespaces Using ‘replaceAll’ & regex

Here,

We will use the concept of Javascript i.e Remove All Whitespace From a String.

const str = ' h   e   l    l  o ';

const noWhitespace = str.replaceAll(/\s/g, '');

console.log(noWhitespace); // 'hello'

Console Output

Example #3: Remove Whitespaces Using ‘replaceAll’

Here,

We will use the concept of Javascript i.e Remove All Whitespace From a String.

const str = ' h   e   l    l  o ';

const noWhitespace = str.replaceAll(' ', '');

console.log(noWhitespace); // 'hello'

Console Output

Example #4: Remove Whitespaces Using ‘split’ & ‘join’

Here,

We will use the concept of Javascript i.e Remove All Whitespace From a String.

const str = ' h   e   l    l  o ';

const noWhitespace = str.split(/\s+/).join('');

console.log(noWhitespace); // 'hello'

Console Output

We hope this article helped you to learn Remove All Whitespace From a String in JavaScript Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5