Design & Download
Your JS Library
in Seconds!!!

Snippet: Trimming Whitespace

Written by Christopher West (cwest) on December 05, 2015.
Removes extra whitespace from the beginning and/or end of strings.
function trim(str) {
  return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}

function trimLeft(str) {
  return str.replace(/^[\s\uFEFF\xA0]+/, '');
}

function trimRight(str) {
  return str.replace(/[\s\uFEFF\xA0]+$/g, '');
}

String.prototype.trim() was officially introduced starting with ECMAScript 5.1. Two non-standard functions that naturally go with this one are String.prototype.trimLeft() and String.prototype.trimRight(). Even though these three functions don't exist in a standardized way across the board, now they can with YourJS:

trim(str) API Documentation

Description

Removes all whitespace characters from the beginning and end of a string.

Parameters

  1. str {string}:
    The string to copy and return with all whitespace characters stripped from the beginning and end of it.

Returns

Returns str with all whitespace characters stripped from the beginning and end of it.

trimLeft(str) API Documentation

Description

Removes all whitespace characters from the beginning of a string.

Parameters

  1. str {string}:
    The string to copy and return with all whitespace characters stripped from the beginning of it.

Returns

Returns str with all whitespace characters stripped from the beginning of it.

trimRight(str) API Documentation

Description

Removes all whitespace characters from the end of a string.

Parameters

  1. str {string}:
    The string to copy and return with all whitespace characters stripped from the end of it.

Returns

Returns str with all whitespace characters stripped from the end of it.