Browsing all articles in JavaScript

LTrim, RTrim and Trim JavaScript Functions

Posted Posted by Cody in JavaScript     Comments View Comments
Dec
22

These are some functions I found online, and it drives me mad having to find them each time. I didn’t write these, but they’ve been passed around a lot. They’re useful if you need some basic JavaScript functions.

Left Trim
Pass it a string to trim and any characters that should be trimmed from the left. chars can be left empty to trim spaces.

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

Right Trim
Works exactly the same as the left trim, just on the right.

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

Trim
Combines the left & right trim to have a full trim functions.

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}