JavaScript

JavaScript: Remove Space From String Examples

Do you wish to remove space from string using JavaScript? In this article, I am going to share examples on how you can remove space between string very easily. Read on to find out more.

How To Remove Space From String Using JavaScript

Let’s assume that we have a string with the word “S t r i n g”. Note that each letter of the word is separated by a space. Now we will remove the space between each of these letters.

Example 1: Remove all spaces completely

<script type="text/javascript">

var original_str = "S t r i n g"

//Strips all spaces
var space_stripped_str = original_str.replace(/\s/g,'');

alert(space_stripped_str + ' <---- Without spaces');

</script>

When you run the above code, you will see an alert that gives you the following output: “String”

Example 2: Remove multiple spaces and replace them with single space

<script type="text/javascript">

var original_str2 = "S    t    r  in  g"
//Strips excessive white spaces i.e. retains only one space between each letter
var white_space_stripped_str = original_str2.replace(/\s+/g, ' ');

alert(white_space_stripped_str + ' <---- With exactly one space between each letter in case each letter has multiple spaces');

</script>

Example 3: Remove spaces completely (trim) from left of the string

<script type="text/javascript">

var original_str3 = "   This is a string"

//Strips all space to the left of the string
alert( original_str3.trimLeft() + ' <--- Without any spaces on the left' );

</script>

Example 4: Remove spaces completely (trim) from right of the string

<script type="text/javascript">

var original_str4 = "This is a string   "

//Strips all space to the right of the string
alert( original_str4.trimRight() + ' <--- Without any spaces on the right' );

</script>
Isn’t that easy? Your Turn Now!

Do you know of any other ways to remove spaces using JavaScript from a word or a string? Please feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*