Javascript How To Remove Extra Spaces From String

Share this Article
Reading Time: 3 minutes
915 Views

Inside this article we will see the concept i.e Javascript how to remove extra spaces from string. In a string, spaces in terms of either normal spaces between words, tabs space in a string, new lines, etc.

All these tabs spaces, new lines, etc will be removed once we implement this concept. If you are wondering to find a solution for removal of extra spaces from string including new lines then this article will help you a lot.

Extra spaces means –

  , tabs, \n new lines

Learn More –

Let’s get started.

Create Simple Application

Here, we will create an application in HTML and using javascript which removes extra spaces from a string value.

Create a file remove-space.html in your localhost directory.

Open file and write this following code into it.

<script>
var stringWithLineBreaks = `
                          Online Web Tutor 
      project 
             I've got 
Breaks
         
`;

console.log(removeNewlines(stringWithLineBreaks));

function removeNewlines(str) {
    //remove line breaks from str
    str = str.replace(/\s{2,}/g, ' ');
    str = str.replace(/\t/g, ' ');
    str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
    console.log(str);
}
</script>

Concept

Here, is the code to remove all spaces from string.

function removeNewlines(str) {
    //remove line breaks from str
    str = str.replace(/\s{2,}/g, ' ');
    str = str.replace(/\t/g, ' ');
    str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
    console.log(str);
}

Application Testing

Open project into browser.

URL: http://127.0.0.1/js/remove-space.html

Output

Online Web Tutor project I've got Breaks

We hope this article helped you to learn Javascript How To Remove Extra Spaces From String in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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?

Get PHP Web Development Courses on Offer in just ₹299
Get PHP Web Development Courses on Offer in just ₹299