Add Space after each Comma in a String using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
5 min

banner

# Table of Contents

  1. Add Space after each Comma in a String in JavaScript
  2. Insert a Space before Capital Letters in a String in JavaScript

# Add Space after each Comma in a String in JavaScript

Use the replaceAll() method to add a space after each comma in a string, e.g. str.replaceAll(',', ', ').

The replaceAll() method will return a new string where all occurrences of a comma are replaced with a comma and a space.

index.js
const str = 'bobby,hadz,com'; const spaced = str.replaceAll(',', ', '); console.log(spaced); // ๐Ÿ‘‰๏ธ "bobby, hadz, com"

add space after each comma in string

The code for this article is available on GitHub

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

For our purposes, we replace each comma with a comma and a space.

The String.replaceAll() 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.

# Add Space after each Comma in a String using replace()

Alternatively, you can use the replace() method.

index.js
const str = 'bobby,hadz,com'; const spaced = str.replace(/,/g, ', '); console.log(spaced); // ๐Ÿ‘‰๏ธ "bobby, hadz, com"

add space after each comma in string using replace

The code for this article is available on GitHub

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:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

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

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

The second argument we passed to the replace method is the replacement string for each match.

If you ever need help reading a regular expression, check out this regular expression cheat sheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

Alternatively, you can use the String.split() method.

# Add Space after each Comma in a String using String.split()

This is a three-step process:

  1. Use the String.split() method to split the string on each comma.
  2. Use the Array.join() method to join the array with a comma and a space separator.
  3. Each comma will be followed by a space in the new string.
index.js
const str = 'bobby,hadz,com'; const spaced = str.split(',').join(', '); console.log(spaced); // ๐Ÿ‘‰๏ธ "bobby, hadz, com"

add space after each comma in string using split

The code for this article is available on GitHub

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:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.
index.js
const str = 'bobby,hadz,com'; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(str.split(','));

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.

This is a more manual approach of replacing each comma with a comma and a space.

# Insert a Space before Capital Letters in a String in JavaScript

You can also use the replace() method to insert a space before the capital letters in a string.

index.js
const str = 'BobbyHadzCom'; const result = str.replace(/[A-Z]/g, ' $&').trim(); console.dir(result); // ๐Ÿ‘‰๏ธ 'Bobby Hadz Com'

insert space before capital letters in string

The code for this article is available on GitHub

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:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

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

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

The square brackets [] are called a character class and match any uppercase Latin letter from A to Z.
index.js
const str = 'BobbyHadzCom'; const result = str.replace(/[A-Z]/g, ' $&').trim(); console.dir(result); // ๐Ÿ‘‰๏ธ 'Bobby Hadz Com'

In other words, the [A-Z] part matches any uppercase letter in the range.

We used the g (global) flag because we want to match each occurrence of an uppercase letter, and not just the first one.

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

The method allows us to specify special replacement strings as parameters.

The $& string inserts the matched substring. In other words, it inserts the uppercase letter that we matched.

index.js
const str = 'BobbyHadzCom'; const result = str.replace(/[A-Z]/g, ' $&').trim(); console.dir(result); // ๐Ÿ‘‰๏ธ 'Bobby Hadz Com'

We have preceded the special string with a space because we want to insert a space before each capital letter.

In its entirety, the regular expression matches every capital letter in the string and replaces it with a space and then the capital letter.

The last step is to use the String.trim() method to remove the leading and trailing spaces from the new string.

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.

If you have to do this often, define a reusable function.

index.js
function addSpaceBeforeCapital(str) { return str.replace(/[A-Z]/g, ' $&').trim(); } // ๐Ÿ‘‡๏ธ Bobby Hadz Com console.log(addSpaceBeforeCapital('BobbyHadzCom')); // ๐Ÿ‘‡๏ธ One Two console.log(addSpaceBeforeCapital('OneTwo'));
The code for this article is available on GitHub

The function takes a string as a parameter and adds a space before each capital letter.

# Insert a Space before Capital Letters in a String using split()

You can also use the String.split() and Array.join() methods to insert a space before each capital letter in a string.

index.js
function addSpaceBeforeCapital(str) { return str.split(/(?=[A-Z])/).join(' '); } // ๐Ÿ‘‡๏ธ Bobby Hadz Com console.dir(addSpaceBeforeCapital('BobbyHadzCom')); // ๐Ÿ‘‡๏ธ One Two console.dir(addSpaceBeforeCapital('OneTwo'));
The code for this article is available on GitHub

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

The regular expression uses a positive lookahead assertion.

index.js
// ๐Ÿ‘‡๏ธ [ 'Bobby', 'Hadz', 'Com' ] console.log('BobbyHadzCom'.split(/(?=[A-Z])/));

Lookahead assertions don't consume a character which allows us to keep the capital letters in the results.

The last step is to join() method to join the array into a string using a space separator.

index.js
// ๐Ÿ‘‡๏ธ Bobby Hadz Com console.log('BobbyHadzCom'.split(/(?=[A-Z])/).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.

If the separator argument is set to an empty string, the array elements are joined without any characters in between them.

# 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.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev