JQuery remove all whitespace from string; Through this tutorial, i am going to show you how to remove all whitespace or unwanted whitespace from the given string in jquery.
Sometimes users can enter whitespaces in the text box, input box, and you want to remove that spaces before storing string, text into the database.
How to remove all whitespace from string in JQuery
There are two functions of jquery which is trim() and replace; This functions are used to remove all whitespaces and unwanted whitespaces from given string.
- jQuery remove unwanted whitespace from string
- jQuery remove all whitespace from string
jQuery remove unwanted whitespace from string
See the following example for how to remove all whitespaces from a string of text using jQuery trim(); as shown below:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Remove All White Spaces from a Strings</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(function () { $('#test').keyup(function () { var text = $.trim($(this).val()); $(".trimmed").html(text); }); }); </script> </head> <body> <h3>Original String</h3> <input id="test" type="text" /> <br> <h3>Trimmed String</h3> <pre class="trimmed"></pre> </body> </html>
Demo for jQuery remove unwanted whitespace from string
Original String
Trimmed String
jQuery remove all whitespace from string
See the following example for how to remove all whitespaces from a string of text using jQuery replace(); as shown below:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Remove All White Spaces from a Strings</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(function () { $('#test1').keyup(function () { var text = $(this).val(); console.log(text); var newMyText = text.replace(/ /g,''); $("#trimmed").html(newMyText); }); }); </script> </head> <body> <h3>Original String</h3> <input id="test1" type="text" /> <br> <h3>Trimmed String</h3> <pre id="trimmed"></pre> </body> </html>
Demo for jQuery remove all whitespace from string
Original String
Trimmed String
Recommended jQuery Tutorials
Recommended:-jQuery Select Multiple Classes
Recommended:-jQuery Registration Form validation using Validator
Recommended:-jQuery Form Validation Custom Error Message
Recommended:-jQuery Get Set and Delete Div Background Image
Recommended:-jQuery Get Current Page URL, Path, Host and hash
Recommended:-jQuery Remove Duplicate Objects from Array
Recommended:-jQuery Convert Image into base64 String
Recommended:-jQuery Range UI Slider With Tooltip, Labels
Recommended:-jQuery Reload or Refresh Page Automatically
Recommended:-jQuery Remove Elements From array and Object
Recommended:-jQuery Remove All Space From String
Recommended:-jQuery Ajax Form Submit FormData Example
Recommended:-jQuery Get and Set Image Src Example