Home > Article > Web Front-end > How to remove spaces from string in jquery?
Jquery method to remove spaces from strings: 1. Use the replace function with regular expressions to find spaces in the string, and replace the spaces with the empty character ['']; 2. Use [$. trim] function to remove spaces at the beginning and end of a string, syntax [$.trim(str)].
Related recommendations: "jQuery Tutorial"
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, This method works for all brands of computers.
Method 1: Use replace() with regular expressions
Remove all spaces [The spaces at both ends include spaces in the middle of the string]:
str = str.replace(/\s+/g,'');
Remove double spaces:
str = str.replace(/^\s+|\s+$/g,'');
Remove left spaces:
str = str.replace( /^\s*/, '');
Remove right spaces:
str = str.replace(/(\s*$)/g,'');
Method 2: $.trim() function
$.trim() function is used to remove whitespace characters at both ends of a string.
Note: The $.trim() function will remove all newline characters, spaces (including consecutive spaces) and tab characters at the beginning and end of the string. If these whitespace characters are in the middle of the string, they are retained and not removed.
Grammar
$.trim( str )
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> <pre id="original"><script> $(function () { var str = " lots of spaces before and after "; $( "#original" ).html( "Original String: '" + str + "'" ); $( "#trimmed" ).html( "$.trim()'ed: '" + $.trim(str) + "'" ); }) </script>