Strip or remove all white spaces using jQuery

jQuery provides a function "trim" which removes the starting and trailing white spaces but the space (/s) within the string are maintained. So if you want to strip or remove all white spaces using jQuery then you can't use trim function. Then what is the solution? Well, You can use regex to find out the white spaces in string and then replace the white space(s). See the code.
//Code Starts
$(document).ready(function(){
    var strVal = '    jQuery By Example     ';
    var iLength = strVal.length;
    $('#spnBefore').html('Length of string is ' + iLength + '');
    strVal = strVal.replace(/ /g,'');
    iLength = strVal.length;
    $('#spnAfter').html('Length of string is ' + iLength + '');
});​
//Code Ends
The regex is using "g" character which means to repeat the search through the entire string.

See result below.



Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..