Javascript replace all spaces with one space

Javascript: Replace multiple spaces with a single space

A lot of standard requirements are there in javascript related to the processing of strings. One such generic requirement is to replace multiple spaces with a single space in a javascript string. This article will discuss and demonstrate how to remove duplicate spaces using various example illustrations.

Table of Contents:-

Replace multiple spaces with a single space using replace() and RegEx

Javascript’s replace() method replaces a particular pattern in the javascript with a replacement. The pattern can be a regular expression, a function, or a string.

Replace multiple spaces with a single space from ” Javascript is the most popular language “

Frequently Asked:

let dummyString = " Javascript is the most popular language "; dummyString = dummyString.replace(/\s+/g, " "); console.log(dummyString);
Javascript is the most popular language

Note: There is a space at the beginning and end of the output string.

Explanation:-

  • Here in the above code replace() function is used. The Regular expression is /\s+/g
  • /and / marks the beginning and end of a pattern.
  • \s+ matches at least one space character within the string.
Читайте также:  New date get date javascript

If we want to remove the spaces from the start and end as well use:

let dummyString = " Javascript is the most popular language "; dummyString = dummyString.trim().replace(/\s+/g, " "); console.log(dummyString);
Javascript is the most popular language

Explanation:-

  • The trim() method will remove the whitespaces from the start and end of the string.
  • Finally, the replace() method will remove the spaces in between the string.

Replace multiple spaces with a single space using split () and join()

Javascript’s split() method returns an array of substrings formed by splitting a given string.

Javascript’s join() method joins the elements of the array back into a string.

Replace multiple spaces with a single space from ” Javascript is the most popular language “

let dummyString = " Javascript is the most popular language "; dummyString = dummyString.trim().split(/[\s,\t,\n]+/).join(' '); console.log(dummyString);
Javascript is the most popular language

Explanation:-

  • The trim() method is used to remove all the spaces from the start and end of the string.
  • The split() method is used to split the string into an array of elements [ ‘Javascript’, ‘is’, ‘the’, ‘most’, ‘popular’, ‘language’ ] . The split is based on space, tab or new line character (\s,\t,\n)
  • Finally, join all the array elements using the join(‘ ‘) method separated by a single space to form a new string.

I hope this article helped you to replace multiple spaces with a single space in a javascript string. Good Luck.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Javascript replace all spaces with one space

Last updated: Feb 15, 2023
Reading time · 4 min

banner

# Replace Multiple Spaces with a Single Space in JavaScript

Use the String.replace() method to replace multiple spaces with a single space, e.g. str.replace(/ +/g, ‘ ‘) .

The String.replace() method will return a new string with all occurrences of multiple, consecutive spaces replaced by a single space.

Copied!
const str = 'bobby hadz com'; // ✅ Replace multiple spaces with a single space const result1 = str.replace(/ +/g, ' '); console.log(result1); // 👉️ "bobby hadz com" // ------------------------------------------------------ // ✅ Replace multiple spaces, tabs, newlines with a single space const result2 = str.replace(/\s+/g, ' '); console.log(result2); // 👉️ "bobby hadz com"

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

The first argument we passed to the method is a regular expression.

The / / characters match the beginning and end of the regular expression.

Copied!
const str = 'bobby hadz com'; const result1 = str.replace(/ +/g, ' '); console.log(result1); // 👉️ "bobby hadz com"

The plus + matches the preceding item (a space) 1 or more times.

With the + , we specify that we want to match 1 or more occurrences of a space, in other words, one or more consecutive spaces.

We used the g (global) flag because we want to match all occurrences of a space in the string and not just the first occurrence.

The second argument we passed to the String.replace() method is the replacement for each match.

In our case, we replace multiple spaces with a single space.

The String.replace() method returns a new string with the matches of the pattern replaced. The method doesn’t change the original string.

Strings are immutable in JavaScript.

# Handling leading or trailing spaces

You might have to handle the scenario where your string contains leading or trailing spaces.

Copied!
const str = ' bobby hadz com '; const result1 = str.replace(/ +/g, ' '); console.dir(result1); // 👉️ ' bobby hadz com '

The string in the example starts and ends with spaces, so the result contains leading and trailing spaces.

You can use the String.trim() method to remove the leading and trailing whitespace before calling replace() .

Copied!
const str = ' bobby hadz com '; const result1 = str.trim().replace(/ +/g, ' '); console.dir(result1); // 👉️ 'bobby hadz com'

The String.trim() method removes the leading and trailing whitespace from a string and returns a new string, without modifying the original string.

The trim() method removes all whitespace characters including spaces, tabs and newlines.

# Replacing multiple whitespace characters with a single space

If you need to replace multiple spaces, tabs and newline characters with a single space, use the following regular expression.

Copied!
const str = 'bobby \n\t\n hadz \n\t\n com'; const result2 = str.replace(/\s+/g, ' '); console.log(result2); // 👉️ "bobby hadz com"

The forward slashes / / mark the beginning and end of the regular expression.

The \s character is used to match spaces, tabs and new lines.

The plus + matches the preceding item (whitespace characters and newline ( \n ) characters) 1 or more times.

The g (global) flag is used to specify that we want to match all occurrences of the regex, and not just the first occurrence.

The second argument we passed to the String.replace() method is the replacement string.

For our purposes, we replace multiple spaces, tabs or newline characters with a single space.

Alternatively, you can use the split() and join() methods.

# Replacing multiple spaces with a single space with split() and join()

This is a two-step process:

  1. Use the split() method to split the string by one or more spaces.
  2. Use the join() method to join the array of substrings with a space separator.
Copied!
const str = ' bobby hadz com '; const result = str.trim().split(/\s+/g).join(' '); console.dir(result); // 👉️ 'bobby hadz com'

We used the String.trim() method to remove the leading and trailing whitespace from the string.

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

Name Description
separator The pattern describing where each split should occur.
limit An integer used to specify a limit on the number of substrings to be included in the array.
Copied!
const str = ' bobby hadz com '; // [ 'bobby', 'hadz', 'com' ] console.log(str.trim().split(/\s+/g));

The last step is to join the array of strings with a space separator.

Copied!
const str = ' bobby hadz com '; // 'bobby hadz com' console.log(str.trim().split(/\s+/g).join(' '));

The Array.join() method concatenates all of the elements in an array using a separator.

The only argument the Array.join() method takes is a separator — the string used to separate the elements of the array.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Remove All Spaces from a String in JavaScript

To remove all spaces from a string in JavaScript, call the replaceAll() method on the string, passing a string containing a space as the first argument and an empty string ( » ) as the second. For example, str.replaceAll(‘ ‘, ») removes all the spaces from str .

const str = 'A B C'; const allSpacesRemoved = str.replaceAll(' ', ''); console.log(allSpacesRemoved); // ABC

The String replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The first argument is the pattern to match, and the second argument is the replacement. So, passing the empty string as the second argument replaces all the spaces with nothing, which removes them.

Note

Strings in JavaScript are immutable, and replaceAll() returns a new string without modifying the original.

const str = 'A B C'; const allSpacesRemoved = str.replaceAll(' ', ''); console.log(allSpacesRemoved); // ABC // Original not modified console.log(str); // A B C 

2. String replace() Method with Regex

Alternatively, we can remove all spaces from a string by calling the replace() method on the string, passing a regular expression matching any space as the first argument, and an empty string ( » ) as the second.

const str = 'A B C'; const allSpacesRemoved = str.replace(/ /g, ''); console.log(allSpacesRemoved); // ABC

We use the g regex flag to specify that all spaces in the string should be matched. Without this flag, only the first space will be matched and replaced:

Источник

Оцените статью