In this post, we will learn how to remove white spaces form a string in jQuery. So how we can do this, we will learn in this post. 


How To Remove White Spaces From A String In jQuery ?


Remove White Spaces From A String

To remove white spaces from a string or text, we use  $.trim()   jQuery method. This method removes the whitespace from the beginning and end of a string. So how this method works we will see in the given example.


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Remove White Spaces From A String In jQuery ?</title>
<style>

h3,
p
{
margin-bottom: 0;
}

#originalText,
#trimmedText
{
background-color: #000;
color: #fff;
display: inline-block;
font-size: 20px;
}

</style>
</head>
<body>

<h3>Original Text</h3>
<pre id="originalText"> CodexRadar </pre>

<button type="button">Remove White Spaces</button>

<h3>Trimmed Text</h3>
<p>Trimmed text will displayed here.</p>
<pre id="trimmedText"></pre>


<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>


<script>

$(document).ready(function(){

$("button").click(function(){

// Get original text
var originalText = $("#originalText").text();

//Trim text
var trimmedText = $.trim(originalText);

//show trimmed text
$("#trimmedText").html(trimmedText);

});

});

</script>
</body>
</html> code-box



Summary

In this post we learned how to remove white spaces form a string in jQuery. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.   

Post a Comment

Previous Post Next Post