In programming trim is a string manipulation function. It will remove the leading and trailing spaces. JavaScript does not provide the trim functionality by default. Best 3 sample i have provided below, same you can use for trimming the string using javascript.
Sample 1: Using Jquery trim: If you are using jquery, you can use the trim as shown below.
//Below code used to remove the trailing and leading space while checking the string is empty if (jQuery.trim(document.getElementById('txtUserName.ClientID')).length==0)
Sample 2: Another sample for javascript trim. It uses the regex function to trim the string.
//using regex trim String.prototype.trim = function() { return this.replace(/^s+|s+$/g, ''); }; function testTrim(){ var myString = " Iam Sandesh "; alert( myString.trim()); }
Sample 3: Below function return the trimmed string.
function trim(str) { str = str.replace(/^s+/,'') for (var i = str.length; i--;) if (/S/.test(str.charAt(i))) return str.substring(0, ++i) return str } function testTrim(){ var myString = " Iam Sandesh "; alert(trim( myString)); }
Hopes above approaches will helps for newbies. If you have any good idea just add comments.
Similar Topics:
- Using jQuery in asp.net application and its advantages
- Javascript Treeview Checkbox Check All function
- Server time in client javascript code