How do you trim a character in javascript?

Update: Was curious around the performance of different solutions and so I've updated a basic benchmark here: https://www.measurethat.net/Benchmarks/Show/12738/0/trimming-leadingtrailing-characters

Some interesting and unexpected results running under Chrome. https://www.measurethat.net/Benchmarks/ShowResult/182877

+-----------------------------------+-----------------------+
| Test name                         | Executions per second |
+-----------------------------------+-----------------------+
| Index Version (Jason Larke)       | 949979.7 Ops/sec      |
| Substring Version (Pho3niX83)     | 197548.9 Ops/sec      |
| Regex Version (leaf)              | 107357.2 Ops/sec      |
| Boolean Filter Version (mbaer3000)| 94162.3 Ops/sec       |
| Spread Version (Robin F.)         | 4242.8 Ops/sec        |
+-----------------------------------+-----------------------+

Please note; tests were carried out on only a single test string (with both leading and trailing characters that needed trimming). In addition, this benchmark only gives an indication of raw speed; other factors like memory usage are also important to consider.


If you're dealing with longer strings I believe this should outperform most of the other options by reducing the number of allocated strings to either zero or one:

function trim(str, ch) {
    var start = 0, 
        end = str.length;

    while(start < end && str[start] === ch)
        ++start;

    while(end > start && str[end - 1] === ch)
        --end;

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trim('|hello|world|', '|'); // => 'hello|world'

Or if you want to trim from a set of multiple characters:

function trimAny(str, chars) {
    var start = 0, 
        end = str.length;

    while(start < end && chars.indexOf(str[start]) >= 0)
        ++start;

    while(end > start && chars.indexOf(str[end - 1]) >= 0)
        --end;

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trimAny('|hello|world   ', [ '|', ' ' ]); // => 'hello|world'
// because '.indexOf' is used, you could also pass a string for the 2nd parameter:
trimAny('|hello| world  ', '| '); // => 'hello|world'

EDIT: For fun, trim words (rather than individual characters)

// Helper function to detect if a string contains another string
//     at a specific position. 
// Equivalent to using `str.indexOf(substr, pos) === pos` but *should* be more efficient on longer strings as it can exit early (needs benchmarks to back this up).
function hasSubstringAt(str, substr, pos) {
    var idx = 0, len = substr.length;

    for (var max = str.length; idx < len; ++idx) {
        if ((pos + idx) >= max || str[pos + idx] != substr[idx])
            break;
    }

    return idx === len;
}

function trimWord(str, word) {
    var start = 0,
        end = str.length,
        len = word.length;

    while (start < end && hasSubstringAt(str, word, start))
        start += word.length;

    while (end > start && hasSubstringAt(str, word, end - len))
        end -= word.length

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trimWord('blahrealmessageblah', 'blah');

Example 1

Remove spaces with trim():

let text = "       Hello World!        ";
let result = text.trim();

Try it Yourself »

Remove spaces with replace() using a regular expression:

let text = "       Hello World!        ";
let result = text.replace(/^\s+|\s+$/gm,'');

Try it Yourself »


Definition and Usage

The trim() method removes whitespace from both sides of a string.

The trim() method does not change the original string.


Syntax

Parameters

Return Value

Type Description
A string A string with removed whitespace from both ends.



Browser Support

trim() is an ECMAScript5 (ES5) feature.

ES5 (JavaScript 2009) fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes 9-11 Yes Yes Yes Yes


String trimming is one of the most common tasks that programmers deal with. Trimming functions remove whitespace from the beginning and/or end of a string. Native support for trimming was introduced in JavaScript 1.8.1, meaning that they were not part of Internet Explorer prior to IE9. This article will show you how to trim, and how you can build more flexible and powerful trimming functions.

JavaScript provides three functions for performing various types of string trimming. The first, trimLeft(), strips characters from the beginning of the string. The second, trimRight(), removes characters from the end of the string. The final function, trim(), removes characters from both ends. Like many other languages, JavaScript’s native functions only remove whitespace characters. Conversely, PHP’s functions can remove arbitrary characters. This article will introduce PHP-like trimming functions.

trimLeft()

Let’s see how the native trimLeft() works.

var string = " Hello world";
console.debug(string.trimLeft());
// prints "Hello world"

Notice that the spaces at the beginning of the string are removed. We can enhance this function by specifying a list of characters to remove. The enhanced version is shown below.

String.prototype.trimLeft = function(charlist) {
if (charlist === undefined)
charlist = "\s";

return this.replace(new RegExp("^[" + charlist + "]+"), "");
};

The key points of this function are the RegExp object and the special ^ character. The RegExp creates a regular expression object that matches text with a given pattern. In regular expressions, the ^ character denotes the beginning of the string. Please note that the input character list is case-sensitive.

The following example shows you how trimLeft() removes spaces at the beginning of a string. This behavior is similar to that of the equivalent native function.

var string = " Hello world";
console.debug(string.trimLeft());
// prints "Hello world"

The following examples show how you can delete a given set of characters from the beginning of the string. The first example trims the lowercase characters “o”, “e”, and “l”, and the uppercase “H”. The second example trims the lowercase “h”. Since the string begins with a capital “H”, no trimming occurs.

var string = "Hello world";
console.debug(string.trimLeft("Hoel"));
// prints " world"

string = "Hi mate!";
console.debug(string.trimLeft("h"));
// prints "Hi mate!"

trimRight()

The enhanced trimRight() function also accepts a single parameter representing the characters to be trimmed. The new trimRight() function is shown below.

String.prototype.trimRight = function(charlist) {
if (charlist === undefined)
charlist = "\s";

return this.replace(new RegExp("[" + charlist + "]+$"), "");
};

The function is quite similar to the previous one. The only difference is the regular expression pattern. Instead of using the ^ character to denote the beginning of the string, we use the $ character, which represents the end of the string.

The next examples show how to use the trimRight() function. The first one is very simple, and is similar to the previous ones. The second, is quite interesting because it uses not just a character list, but a POSIX character class. Character classes are shorthand notation to specify sets of characters. The example uses the W code. W represents non-word characters, or all characters except letters, digits, and the underscore character.

var string = "Hello world";
console.debug(string.trimRight("odl"));
// prints "Hello wor"

string = "Hi mate!";
console.debug(string.trimRight("\W"));
// prints "Hi mate"

trim()

The last function is very simple, and relies on the previous two. It trims both at the beginning and the end of the string. Its implementation is simple too, because it consists of calling trimLeft() and then trimRight() on the same string.

String.prototype.trim = function(charlist) {
return this.trimLeft(charlist).trimRight(charlist);
};

Some examples of using trim() are shown below.

var string = "he loves she";
console.debug(string.trim("hes "));
// prints "lov"

string = " I write for JSPro.com ";
console.debug(string.trim());
// prints "I write for JSPro.com"

Conclusions

A trim function is useful for removing extra spaces typed by users. Often times, users aren’t even aware that they typed extra spaces. This fact could also lead to login problems if, for example, a user registered himself with a trailing whitespace. However, this is not the only use case for trimming. Using the enhanced versions of the trim functions presented in this article, you’ll also be able to solve a wider range of problems than the native ones can solve.

How do you trim a string in JavaScript?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

How do I trim a string to a specific character?

Regular Expression (RegEx) is the easiest way to trim a specific character from a string in JavaScript. Use the JavaScript replace() method with RegEx to remove a specific character from the string. The example code snippet helps to remove comma ( , ) characters from the start and end of the string using JavaScript.

Does JavaScript have a trim function?

JavaScript String trim() The trim() is a built-in string function in JavaScript, which is used to trim a string. This function removes the whitespace from both the ends, i.e., start and end of the string.

How do you trim the value of a string?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.