Trim any character from the ends of the String in JavaScript

Javascript provides a method on string objects to trim off spaces from the end. But there are times when you want to trim any character from the ends of the string.

One of the best things I like about JavaScript is that fact that it is highly extensible. You can easily extend classes, override methods and do things which are not initially supported by JavaScript. In today’s tutorial we will be implementing a trim function that not only trims spaces from both ends of string, but also trims the passed parameter string.

Before we proceed lets see how trim function actually works in JavaScript. Trim function in JavaScript only removes white spaces from both sides of the string. Even if you pass parameters to it, it does nothing else.

Our usecase

We want to create a trim function that accepts parameters and trims the passed string from both ends of the string. Also, we will be adding this new trim method to the prototype of string, hence making it accessible like a method of string elements. So, lets get started.

function processString(s, c) {
  if (c === "]") c = "\\]"
  if (c === "\\") c = "\\\\"

  if (c == "" || c == undefined || c == null) return s.trim()

  return s.replace(new RegExp("^" + c + "+|" + c + "+$", "g"), "")

This method that we have written above does the trimming part of the string. It takes two parameters s(string) and c(what to trim) and the regex replaces c with blank character. To add this trim function to the prototype of string, use the code below.

String.prototype.newTrim = function (c) {
  if (c === "]") c = "\\]"
  if (c === "\\") c = "\\\\"

  if (c == "" || c == undefined || c == null) return this.trim()

  return this.replace(new RegExp("^" + c + "+|" + c + "+$", "g"), "")

So, thats a wrap. Please let me know if you ran into any issues. :)