This is what you want:

function ltrim(str) {
  if(!str) return str;
  return str.replace(/^\s+/g, '');
}

Also for ordinary trim in IE8+:

function trimStr(str) {
  if(!str) return str;
  return str.replace(/^\s+|\s+$/g, '');
}

And for trimming the right side:

function rtrim(str) {
  if(!str) return str;
  return str.replace(/\s+$/g, '');
}

Or as polyfill:

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

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

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

Note:
\s: includes spaces, tabs \t, newlines \n and few other rare characters, such as \v, \f and \r.
\uFEFF: Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
\xA0: ASCII 0xA0 (160: non-breaking space) is not recognised as a space character

Answer from Stefan Steiger on Stack Overflow
Top answer
1 of 10
48

This is what you want:

function ltrim(str) {
  if(!str) return str;
  return str.replace(/^\s+/g, '');
}

Also for ordinary trim in IE8+:

function trimStr(str) {
  if(!str) return str;
  return str.replace(/^\s+|\s+$/g, '');
}

And for trimming the right side:

function rtrim(str) {
  if(!str) return str;
  return str.replace(/\s+$/g, '');
}

Or as polyfill:

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

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

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

Note:
\s: includes spaces, tabs \t, newlines \n and few other rare characters, such as \v, \f and \r.
\uFEFF: Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
\xA0: ASCII 0xA0 (160: non-breaking space) is not recognised as a space character

2 of 10
42

Try to use javascript's trim() function, Basically it will remove the leading and trailing spaces from a string.

var string=' This is test';
string = string.trim();

DEMO

So as per the conversation happened in the comment area, in order to attain the backward browser compatibility just use jquery's $.trim(str)

var string=' This is test';    
string = $.trim(string)
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › trim
String.prototype.trim() - JavaScript - MDN Web Docs
July 10, 2025 - The trim() method of String values removes whitespace from both ends of this string and returns a new string, without modifying the original string.
🌐
ReqBin
reqbin.com › code › javascript › zcdulg8f › javascript-trim-string-example
How to trim a string using JavaScript?
To trim strings in JavaScript, you need to use the string.trim() method. The method removes all of the spaces and line separators both at the beginning and end of the string.
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › String › trim
JavaScript String trim() - Remove Leading/Trailing Spaces | Vultr Docs
November 8, 2024 - This example demonstrates how trim() is used to clean up 'greeting'. The resulting output is 'Hello world!' without the leading and trailing spaces. Recognize that trim() also removes tab, carriage return, and newline characters from the start ...
🌐
DEV Community
dev.to › natclark › removing-whitespace-from-strings-in-javascript-4k32
Removing Whitespace From Strings in JavaScript - DEV Community
September 7, 2021 - However, "Example string" (with two spaces) will become "Example string" (with one space). If you just want to remove the trailing whitespace at the beginning and end of a string (if any), the trim() function is what you're looking for:
🌐
TechOnTheNet
techonthenet.com › js › string_trim.php
JavaScript: String trim() method
The trim() method returns a string with whitespace characters removed from the start and end of the string. The trim() method does not change the value of the original string. Let's take a look at an example of how to use the trim() method in JavaScript. ... In this example, we have declared ...
🌐
Go Make Things
gomakethings.com › articles › how-to-remove-white-space-from-the-beginning-or-end-of-a-string-with-vanilla-js
How to remove white space from the beginning or end of a string with vanilla JS | Go Make Things
April 1, 2020 - Today, we’re going to look at a few different ways to remove whitespace from the start or end of a string with vanilla JavaScript. Let’s dig in. You can call the trim() method on your string to remove whitespace from the beginning and end of it.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript string methods › string.prototype.trim()
JavaScript trim() Method
November 3, 2024 - Summary: in this tutorial, you’ll learn how to use the JavaScript trim() method to remove whitespace characters from both ends of a string. The String.prototype.trim() returns a new string with whitespace trimmed from the beginning and end ...
Find elsewhere
🌐
Stack Abuse
stackabuse.com › how-to-trim-whitespacescharacters-from-a-string-in-javascript
How to Trim Whitespaces/Characters from a String in JavaScript
May 22, 2023 - JavaScript provides three functions to assist us in trimming strings entering into our database or application from input fields. trim() is a built-in string method which is used to, well, trim a string. The method removes whitespace from both ends of a string and returns it: ... Let's create ...
🌐
ASPSnippets
aspsnippets.com › Articles › 3226 › JavaScript-Remove-whitespace-from-Beginning-Start-and-End-of-String
JavaScript Remove whitespace from Beginning Start and End of String
December 30, 2020 - RemoveWhitespace JavaScript function is called. Inside the function, first the TextBox is referenced and then the whitespace is removed from beginning (start) and end of the string using the JavaScript
🌐
W3Schools
w3schools.com › jsref › jsref_trim_string.asp
JavaScript String trim() Method
The trim() method removes whitespace from both sides of a string.
Top answer
1 of 3
13
  • \s means whitespace characters in regex, like space, tab, etc.
  • ^ means the beginning of the string
  • $ means the end of the string
  • | means OR (match the left side or the right side)
  • + means 1 or more (based off of the rule on the left)
  • /a regex/g the g means "global", aka "match multiple times" since you could need to match at the beginning AND end

So the regex means:

/^\s+|\s+$/g
/         /       Wrap the regex (how you do it in JS)
 ^\s+             Try to match at the beginning one or more whitespace chars
     |            Or...
      \s+$        Try to match whitespace chars at the end
           g      Match as many times as you can

String.prototype.replace replaces the match(es) found in the regex with the string provided as the 2nd argument, in this case an empty string.

So the process internally is:

  1. Look for all sections that match the regex (which will be the whitespace at the beginning and the whitespace at the end
  2. Replace each match with "", removing those matches entirely

let hello = "   Hello, World!  ";
let wsRegex = /^\s+|\s+$/g; 
let result = hello.replace(wsRegex, "");

console.log('"' + result + '"');
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Most people use String.prototype.replaceAll instead of .replace when they use the global flag

let hello = "   Hello, World!  ";
let wsRegex = /^\s+|\s+$/g; 
let result = hello.replaceAll(wsRegex, "");

console.log('"' + result + '"');
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 3
0

The second argument of replace is for what you will replace from the match(es) of the first argument.

The regex will match/select the spaces on the beginning (^) and on the end ($) of the string, and then will be replaced by "".

When you use the regex /(\S)/g you're matching everything but spaces, in this case you will use something like hello.replace(/(\S)/g, '$1');

$1 means the first group of your regex.

🌐
GeeksforGeeks
geeksforgeeks.org › how-to-remove-spaces-from-a-string-using-javascript
How to Remove Spaces From a String using JavaScript? | GeeksforGeeks
The trim() method is used to remove the white spaces from the beginning and end of a string. Syntax: jQuery.trim( str ) Parameter: This method accepts a single ... Given a Date Object and the task is to remove the time portion from the object ...
Published   November 14, 2024
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-trim-a-string-at-beginning-or-ending-in-javascript
How to trim a string at beginning or ending in JavaScript? - GeeksforGeeks
July 23, 2025 - ... const str = " GeeksforGeeks "; // Trimming the string at the start let newStr = str.trimStart(); console.log("Modified String: " + "'" + newStr + "'"); ... JavaScript trimEnd() Method is used to eliminate white-space from the end of a string.
🌐
TutorialsPoint
tutorialspoint.com › how-to-trim-a-string-at-beginning-or-ending-in-javascript
JavaScript String trimStart() Method
February 16, 2023 - The JavaScript String trimStart() method removes whitespace characters from the beginning (left side) of the current string. It returns a new string without modifying the original string.
🌐
Latenode
community.latenode.com › other questions › javascript
Removing leading and trailing spaces in JS strings - JavaScript - Latenode Official Community
March 13, 2025 - Hey everyone! I’m working on a project and I need some help with string manipulation in JavaScript. I want to clean up user input by getting rid of any extra spaces at the beginning and end of the text. What’s the best w…
🌐
jQuery
api.jquery.com › jQuery.trim
jQuery.trim() | jQuery API Documentation
Unlike jQuery.trim, String.prototype.trim does not work with types other than strings (null, undefined, Number). Make sure that your code is compatible when migrating. The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of ...
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Remove whitespace from start and end (Regex) - JavaScript - The freeCodeCamp Forum
September 5, 2023 - /^\s+|\s+$/g I am getting bit confused here, could someone explain why do I need to put the or in between ,shouldn’t the + look for multiple spaces and it is supposed to work without using |?
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Remove whitespace Best Practice !? - Curriculum Help - The freeCodeCamp Forum
May 13, 2019 - hi everyone if you could rate my solution for that challenge, could you consider it Best Practice or Less or More (Average) or Newbie?? here my solution: let hello = " Hello, World! "; let wsRegex = /\s/g; // Change this line let result = hello.replace(wsRegex, "").replace(/,/g, ", "); // Change this
🌐
Latenode
community.latenode.com › other questions › javascript
How to remove whitespace from beginning and end of text in JavaScript - JavaScript - Latenode Official Community
August 26, 2025 - I’m working on a JavaScript project and I need to clean up user input by removing extra spaces. I have strings that sometimes have spaces, tabs, or other whitespace characters at the beginning or end. For example, when u…