How To Trim String In Javascript

Getting started

Trim method is used to remove the white spaces from the supplied data before validation and inserting data into the database. if the white spaces occur in the middle of the string it will be in the existing state. 

trim()

The trim() method is used to remove the white spaces from the beginning and end of the string. Look at the following example to trim the string.

var value = " some string ";
console.log(value.trim());
// prints "some string"

if you are using JQuery library you can use $.trim() to remove the white spaces. Look at the below example to remove white spaces using jquery.

var str = " some string ";
var trimmedString = $.trim(str);

console.log(trimmedString);
// prints "some string"

trimLeft()

trimLeft() method is used to remove the white spaces from the beginning of the supplied string. The following example will show you how to trimLeft() the string.

var value = " some string";
console.log(value.trimLeft());
// prints "some string"

trimRight()

trimRight() method is used to remove the white spaces from the end of the supplied string. Look at the following example to trimRight() the string.

var value = "some string ";
console.log(value.trimRight());
// prints "some string"