Remove All White Spaces From Text Using jQuery

In this tutorial, learn how to remove all white spaces from text using jquery. The short answer is: use replace() of jQuery and mention the space you want to remove. The string may contain extra spaces which you can remove easily with this method.

After removal of all the space from the string. You will get a string whose words are closely placed without a single space.

This may not prefer in some situations but is helpful in some places. Where you don’t want a single piece of space in the text.

Method 1: Remove All White Spaces From Text in jQuery replace()

To remove the white spaces from a string, you have to use jQuery text() first. After you get the string in a variable, you have to use replace() to remove all white spaces.

Test it Live

Output

This is my string.

The above example contains a piece of text and the button with the class name. The string contains spaces after each word. Click the above button to remove all the spaces from the text. This generates a new string with no spaces at all.

Method 2: Using jQuery split() and join() to Trim All Whitespaces From String

If you want to trim all whitespace from a string, you can use the jQuery split() with join() function. Also, pass the space within quotes (‘ ‘) as the argument of the split() function. See the example given below to trim whitespaces.

Output

Welcome to TutorialDeep.

When you click the above button, you will get trimmed whitespaces in the output. The two function checks for all the whitespaces. After that, it removes them one by one to give results without whitespaces.

Method 3: Using jQuery replace() and RegExp() to Replace Spaces of Text

In addition to the above methods, you can also use the replace() with RegExp() function. The RegExp() function takes two arguments in which the first argument is the whitespace to replace with the text content. The second argument is ‘g’ which means global to scan the specified string that is whitespace.

Output

How are you today?

You have to click the button given above to replace all the spaces from the given string. When you click the button, you will get a string without any white spaces.

You May Also Like Read.

I hope you like this tutorial on how to remove all white spaces from text using jquery.