How to Trim String in JavaScript ?

Introduction

When you are programming and you need to manipulate string it's common that you need to remove spaces at the beginning and end of a string. In Javascript you can use the trim() function to remove paces.

In this tutorial we are going to explain how to remove spaces using trim and without trim. When we don't use trim function we can do left or right trim on the string.

Removing spaces using trim

In javascript to execute the trim function you can use it like the following example:

    var text="     How to remove spaces on this string     ";
    var trimmedText = text.trim();
    console.log(text);
    console.log(trimmedText);

Removeing spaces without trim

You can use replace with regex to remove spaces like the following example:

var text="     How to remove spaces on this string     ";
trimmedText = str.replace(/^s+|s+$/gm,'');

Using replace allow us to trim on the left side with javascript:

var text="     How to remove spaces on this string     ";
ltrimmedText = str.replace(/^s+/,'');

And this is the example code of javascript on hwo to trim only the right part:

var text="     How to remove spaces on this string     ";
rTrimmedText = str.replace(/s+$/,'');