Browsing all articles tagged with javascript functions
LTrim, RTrim and Trim JavaScript Functions
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);
}
Posted by Cody in