Javascript Trim, Ltrim and Rtrim functions

This Javascript code trim implementation removes all leading and trailing occurrences of a set of characters specified. If no characters are specified it will trim whitespace characters from the beginning or end or both of the string.

Javascript

This function willl trim these characters:

” ” (ASCII 32 (0×20)), an ordinary space.
“ ” (ASCII 9 (0×09)), a tab.
“ ” (ASCII 10 (0x0A)), a new line (line feed).
“ ” (ASCII 13 (0x0D)), a carriage return.
“″ (ASCII 0 (0×00)), the NUL-byte.
“x0B” (ASCII 11 (0x0B)), a vertical tab.

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

Share the love

0 comments

ed hardy
Mon, 18th January 2010
good Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement