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.



Responsive Menu
Add more content here...