Javascript String Trim with Javascript Trim Function Examples
Just as in many programming languages, in Javascript too, programmers and developers frequently require trimming functions and trim codes in order to manipulate string or text values and variables.
Although many programming and scripting languages have built-in methods for string trimming, Javascript does not have a built-in method or a Javascript trim function.
What is Trimming, TRIM, LTRIM, RTRIM Functions ?
To trim string is removing whitespace like spaces from a string variable.
If the code trim leading spaces then this trim function is called LTRIM.
If the code trim trailing white space then this trim function is called RTRIM.
LTRIM can be considered as Left Trim which is trimming a string or a text from left side.
RTRIM can be considered as Right Trim which is trimming a string or a text from right hand side.
So string TRIM function is the combination of these two LTRIM and RTRIM string strip functions.
General Look at Javascript TRIM Functions ?
It is possible to create a javascript trim function which loops through all of the characters in a given string and remove the white space from the string one by one until a valid string character is reached for LTRIM.
And by using the same approach, starting from the end of the string variable it is possible to remove the trailing spaces until a string character is found in the loop for RTRIM.
You can even reverse the string for the RTRIM and use the same javascript code you have built for LTRIM.
But instead of using a javascript loop which is not a preferred way of coding, I can suggest using regular expressions with Javascript to strip string values.
Javascript Trim Function using Loop in the Characters of the String with While
In the below javascript trim function, we develop string trimming code to trim string with one of the javascript loop commands While.
Javascript Trim Function Example
In the below Javascript trim method code example, the trim functions including ltrim and rtrim take the string or the text value as an argument of the trim function, and returns the text after white spaces are removed from the input string.
Javascript String Trim Prototype Example
It is also possible for Javascript developers to add the trim method to the String object's prototype.
Adding the trim functions to the String object prototype and including the script file as a global javascript include will enable developers to use trim methods everywhere in the web pages.
You can use these sample javascript trim functions in your button OnClick() actions, or in textbox 's onBlur() events, etc.