How to remove spaces from string using JQuery?

In this post we will show you How to remove spaces from string using JQuery, hear for How to remove spaces from string using JQuery we will give you demo and example for implement.

In this post, we would like to share with you how to remove all white spaces or blank space from a string using jquery.

how to remove Spaces from the string (leading and trailling spaces)?

Actually, we may sometime require to delete all empty spaces from string using jquery javascript. we can easily remove all black space using jquery replace function.

Here we give you very small example with one rich textbox and add button bellow. You have to simple add string on rich text box then click on button it will remove spaces from added string.

jQuery Remove All whitespace Spaces Example
jQuery Remove All whitespace Spaces Example

It’s very simple example and also we give you demo for this you can see bellow button. You are able to download code for remove spaces using jquery. So let’s see bellow example.

Read Also:  Simple Jquery ajax request example with demo

index.html

<html lang="en">
<head>
    <title>Jquery - Remove white space from string - www.pakainfo.com</title>  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<div class="demoExample">
  Hi   Hello  How are You   Dear Friends.
</div>

<script type="text/javascript">
      var myText = $(".demoExample").text();
      var results = myText.replace(/ /g,'');
      alert(results);
</script>
</body>
</html>

use the jQuery $.trim() function to remove all the spaces.

  • including non-breaking spaces
  • newlines
  • tabs from the beginning
  • tabs end of the specified string.

Example 2: Jquery trim method with the help of live example.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Remove White Space from Strings - www.pakainfo.com</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        var myText = $(".original").text();
        var dataCont = $.trim(myText);
        $(".results").html(dataCont);
    });
</script>
</head>
<body>
    <h3>Original String</h3>
    <pre class="original">      Tamilrokers of Movies with       Pakainfo    Black   spaces Hindi and English.       </pre>
    <br>
    <h3>Trimmed String</h3>
    <pre class="results"></pre>
</body>
</html>

Remove extra spaces from a string

<script>
var results = "   Hello Pakainfo  .  Welcome ,    Do you love Pakainfo , Pakainfo  ? ";
document.write(results.replace("\\s+", " ").trim());
</script>

I hope you get an idea about jquery trim characters from end of string.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.