Lad Who Codes

Implementing Trim Function in JavaScript

Posted by Dinesh Verma on Friday 17 August 2018

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. :)

Post a Comment