Back Javascript

Javascript Trim, Ltrim and Rtrim functions

WRITTEN BY ON 07 Apr 2011
17,013 VIEWS • SHARES
0 comments

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"), "");
}
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.