LTrim(),RTrim(), Trim() function are very popular functions in many programming languages such as C#,Java… which can delete leading or trailing spaces of any string. But Javascript does not support these function,it’s so sad:(!
In this article, I show you the way of making these function by creating simple algorithm to replace spaces based on only function SubString() which Javacript supports.
Function LTrim() – Delete leading spaces of a string
function LTrim(text) { while (text.substring(0, 1) == ' ') { text = text.substring(1, text.length); } return text; } |
var text = " 4rapiddev.com"; text = LTrim(text) // Output : text = "4rapiddev.com"; |
Function RTrim() – Delete trailing spaces of a string
function RTrim(text) { while (text.substring(text.length - 1, text.length) == ' ') { text = text.substring(0, text.length - 1); } return text; } |
var text = "4rapiddev.com "; text = RTrim(text) // Output : text = "4rapiddev.com"; |
Function Trim() – delete leading or trailing spaces of a string
function Trim(text) { return LTrim(RTrim(text)); } |
var text = " 4rapiddev.com "; text = Trim(text) // Output : text = "4rapiddev.com"; |
Only function Trim() in case you do not need LTrim and RTrim function
function Trim(text) { // Left Trim while (text.substring(0, 1) == ' ') { text = text.substring(1, text.length); } // Right Trim while (text.substring(text.length - 1, text.length) == ' ') { text = text.substring(0, text.length - 1); } return text; } |
Javascript Trim Function Source code for testing