One line is enough:

var x = '|f|oo||';
var y = x.replace(/^\|+|\|+$/g, '');
document.write(x + '<br />' + y);

^     beginning of the string
\|+   pipe, one or more times
|     or
\|+   pipe, one or more times
$     end of the string

A general solution:

function trim (s, c) {
  if (c === "]") c = "\\]";
  if (c === "^") c = "\\^";
  if (c === "\\") c = "\\\\";
  return s.replace(new RegExp(
    "^[" + c + "]+|[" + c + "]+$", "g"
  ), "");
}

chars = ".|]\\^";
for (c of chars) {
  s = c + "foo" + c + c + "oo" + c + c + c;
  console.log(s, "->", trim(s, c));
}

Parameter c is expected to be a character (a string of length 1).

As mentionned in the comments, it might be useful to support multiple characters, as it's quite common to trim multiple whitespace-like characters for example. To do this, MightyPork suggests to replace the ifs with the following line of code:

c = c.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');

This part [-/\\^$*+?.()|[\]{}] is a set of special characters in regular expression syntax, and $& is a placeholder which stands for the matching character, meaning that the replace function escapes special characters. Try in your browser console:

> "{[hello]}".replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
"\{\[hello\]\}"
Answer from user1636522 on Stack Overflow
Top answer
1 of 16
302

One line is enough:

var x = '|f|oo||';
var y = x.replace(/^\|+|\|+$/g, '');
document.write(x + '<br />' + y);

^     beginning of the string
\|+   pipe, one or more times
|     or
\|+   pipe, one or more times
$     end of the string

A general solution:

function trim (s, c) {
  if (c === "]") c = "\\]";
  if (c === "^") c = "\\^";
  if (c === "\\") c = "\\\\";
  return s.replace(new RegExp(
    "^[" + c + "]+|[" + c + "]+$", "g"
  ), "");
}

chars = ".|]\\^";
for (c of chars) {
  s = c + "foo" + c + c + "oo" + c + c + c;
  console.log(s, "->", trim(s, c));
}

Parameter c is expected to be a character (a string of length 1).

As mentionned in the comments, it might be useful to support multiple characters, as it's quite common to trim multiple whitespace-like characters for example. To do this, MightyPork suggests to replace the ifs with the following line of code:

c = c.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');

This part [-/\\^$*+?.()|[\]{}] is a set of special characters in regular expression syntax, and $& is a placeholder which stands for the matching character, meaning that the replace function escapes special characters. Try in your browser console:

> "{[hello]}".replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
"\{\[hello\]\}"
2 of 16
96

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');
๐ŸŒ
Mastering JS
masteringjs.io โ€บ tutorials โ€บ fundamentals โ€บ trim
How to Trim Characters from a String in JavaScript - Mastering JS
To trim multiple characters, broaden ... example.replace(/[0-9]+/, ''); // Mastering JS ยท JavaScript strings also have trimStart() and trimEnd() methods....
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ trim
String.prototype.trim() - JavaScript - MDN Web Docs
The trim() method of String values removes whitespace from both ends of this string and returns a new string, without modifying the original string.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-remove-char-from-string
JS Remove Char from String โ€“ How to Trim a Character from a String in JavaScript
May 9, 2024 - You can remove leading and trailing whitespace characters from a string using the built-in trim() method. ... The trim() method is called directly on the string you want to trim.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ how do i remove/chop/slice/trim off the last character in a string using javascript?
How do I remove/chop/slice/trim off the last character in a string using Javascript? | Sentry
Strings in JavaScript are immutable, so whenever we want to manipulate one, we must create a new string with our desired changes. Therefore, to remove the last character of a string, we must create a new string that excludes it.
๐ŸŒ
Dmitri Pavlutin
dmitripavlutin.com โ€บ javascript-string-trim
How to Trim Strings in JavaScript - Dmitri Pavlutin
November 25, 2021 - phoneNumber.trimEnd() trims the end of the string too. '\t 555-123\n ' becomes '\t 555-123'. The whitespaces, like a space or tab, are special characters that create empty space when rendered. Also the line terminals, like the line feed, you may find at the end of lines in a multiline string. Often you may find it useful to remove these special characters from a string. The JavaScript trim functions can help you.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ trimEnd
String.prototype.trimEnd() - JavaScript - MDN Web Docs
July 10, 2025 - "; console.log(greeting); // Expected output: " Hello world! "; console.log(greeting.trimEnd()); // Expected output: " Hello world!"; ... A new string representing str stripped of whitespace from its end (right side). Whitespace is defined as white space characters plus line terminators.
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 - Moving on, let's now see how to trim all whitespace using Regular Expressions. So far we have only seen how to remove whitespace from the start or end of our strings - let's now see how to remove all whitespace. This is possible using the JavaScript's string.replace() method, which supports Regular Expressions (RegEx) and helps find matches within a particular string.
๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ javascript โ€บ trimming strings in javascript
Trimming Strings in JavaScript โ€” SitePoint
November 6, 2024 - The trim() method in JavaScript is used to remove whitespace from both ends of a string. Whitespace in this context includes all the blank spaces, tab spaces, and line terminator characters like LF (Line Feed) and CR (Carriage Return). Itโ€™s important to note that this method does not change ...
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ javascript โ€บ examples โ€บ trim-a-string
JavaScript Program to Trim a String | Vultr Docs
December 17, 2024 - The replace() method uses this pattern to remove all leading and trailing hash characters. Trimming strings in JavaScript is straightforward using built-in methods like trim(), trimStart(), and trimEnd() to deal with conventional whitespace issues.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ javascript โ€บ standard-library โ€บ String โ€บ trim
JavaScript String trim() - Remove Leading/Trailing Spaces | Vultr Docs
November 8, 2024 - The trim() method is an essential tool in JavaScript for maintaining clean, user-friendly data handling by removing unwanted spaces, tabs, and newline characters from strings. Its simplicity allows it to be seamlessly integrated with other string ...
๐ŸŒ
JavaScript Tutorial
javascripttutorial.net โ€บ home โ€บ javascript string methods โ€บ string.prototype.trim()
JavaScript trim() Method
November 3, 2024 - In this example, we use the trim() method to remove the leading and trailing whitespace from a string and then use the split() method to split the string into two parts. Use the trim() to remove whitespace characters from both ends of a string.
๐ŸŒ
Futurestud.io
futurestud.io โ€บ tutorials โ€บ right-trim-characters-off-a-string-in-javascript-or-node-js
Right-Trim Characters Off a String in JavaScript or Node.js
February 23, 2023 - Hereโ€™s a sample function removing whitespaces or provided characters from the end of a string: /** * Removes whitespaces from the tail of the string when * no argument value is present. It trims the provided `character` * from the end of the string if you pass along a value.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ bytes โ€บ trim-the-last-n-characters-from-a-string-in-javascript
Trim the Last N Characters from a String in JavaScript
August 21, 2023 - This Byte will show you two ways to achieve this: using the String.substring() method and conditionally removing the last N characters. The String.substring() method returns a new string that starts from a specified index and ends before a second specified index. We can use this method to trim the last N characters from a string.
๐ŸŒ
Byby
byby.dev โ€บ js-string-trim-char
How to trim characters from a string in JavaScript
Using trim(), trimStart() and trimEnd() methods of the String object. These methods remove whitespace characters from both ends, the beginning or the end of a string, respectively.
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ javascript โ€บ zcdulg8f โ€บ javascript-trim-string-example
How to trim a string using JavaScript?
To remove spaces from a string using JavaScript, you can use the string.trim() method. The trim() method removes spaces from both ends of a given string without changing the original string.
๐ŸŒ
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 - JavaScript trim() Function: Trim() eliminates whitespace from both ends of a string and produces a new string with no changes to the original. All whitespace characters and all line terminator characters are considered whitespace in this context.