How to Remove Spaces from String in jQuery

November 8, 2021
Jquery
How to Remove Spaces from String in jQuery

In this tutorial, you will learn how to remove spaces from string in jquery.

One of the common problems is to remove the spaces from the string.

In this blog post, you will learn how to remove all those spaces in jquery and how to remove the only first and last spaces in jquery as well.

Let’s get started.

Remove all spaces from a string:

let text="this is text";
let new_text=text.replace(/ /g,'');
console.log(new_text)

In this above, replace(/ /g,'') will allow to remove all the spaces from the string. The output of the above code will be thisistext .

Remove first and last spaces only from a string:

Jquery has the $.trim function to remove the first and last spaces from the string. Moreover, it is also used for removing non-breaking spaces, newlines, and tabs spaces as well.

let text=" this is text ";
let new_text= $.trim(text);
console.log(new_text)

The output of the above code will be this is text .

Conclusion:

Hope you have learned today on removing all those spaces in jquery and removing the only first and last spaces in jquery as well.

Let me know if you have any questions and I will see you in the next one.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon