All articles
javascript

Trim spaces for String in JavaScript

Share this article

Share on LinkedIn Share on X (formerly Twitter)

The trim() method returns a new string after removing the whitespace characters the beginning and the end of the original string. Whitespace here refers to any one of these: space, tab, no-break space, etc., and also all the line terminator characters: LF, CR, etc.,.

'You are awesome !  '.trim(); //'You are awesome !'
'   AWSM! '.trim(); //'AWSM!'
'AWSM  '.trim(); //'AWSM'

Polyfill

You can use this polyfill script in your code before you use trim(), so that this code will create trim(), if it is not available in your JavaScript environment.

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Comments