How to Remove spaces from String jQuery
To remove spaces from string from starting and end of supplied string, you can use jQuery $.trim() function. This function can remove non-breaking spaces, tabs and newlines from the starting and end of string.
This trim function keep whitespace characters in the middle of the string.
Syntax: $.trim(string);
Example to Remove Whitespace from String using trim() function:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var oldStr = $(".oldstring").text();
var newStr = $.trim(oldStr);
$(".trimmedString").html(newStr);
});
</script>
</head>
<body>
<h3>String with spaces at starting and end position</h3>
<pre class="oldstring"> Hi, this is original string </pre>
<br>
<h3>Trimmed String</h3>
<pre class="trimmedString"></pre>
</body>
</html>Another Method Remove all Spaces from Srting:
If you need to delete spaces from string from any position including in between, use replace() function.
Check below code example:
<script type="text/javascript">
var myStr = 'Hi , how are you ?';
var trimmedText = myStr.replace(/ /g,'');
alert(trimmedText);
</script>