How to Remove String Spaces and Dash Using jQuery

In this tutorial, learn how to remove string spaces, dash, or hyphens using jQuery. The short answer is to use the replace() function of jQuery to delete hyphens and spaces from string characters.

The hyphen or dash is the character ‘-‘ to remove from the string with jQuery. You can also remove the spaces from the beginning or end of the string. The white space can be one or more than one in the given string.

Let’s find out the different methods of removing spaces with the examples given below.

How to Remove All String Spaces Using jQuery

If you want to remove all the white spaces from the string, you have to use jQuery text() and replace(). The text() first get the text content from the string. After that, the replace() function replaces all the white spaces from the string.

Example

Test it Live

Output

This is my string


The above example contains the button and the string content with spaces. You have to click the button given above to remove string spaces between its words in the output. The new string generated in the output has no space.

Remove Dash or Hyphen(-) Character From String Using jQuery

In addition to all the above examples, you can also remove special characters like hyphen (-) and symbols (like $) from the string. To remove the special characters like a dash(-) or hyphen, you can use the same method using replace() given above and change the space with the hyphen or symbol as given below.

Output

This-is-my-string


The above example contains the special character dash(-) among string letters. Click the above button to remove the dash(-) from the string. Check the output you get after clicking the button.

Eliminate Extra White spaces From the Beginning, Middle, and End Using jQuery

If you want to eliminate extra white spaces from the beginning, middle, and end, you have to use the jQuery trim() function that removes extra white spaces from the string. You have to first use the text() to get the text content of the string. After that, you can use the trim() as given below.

Output

   This   is    my     string


The above example contains the string with some extra spaces in every word from the start to the end. You can click the button given above to eliminate the start and end spaces.

You May Also Like to Read

I hope you like this tutorial on how to remove string spaces and dash using jQuery.

References