Javascript: String Replace Space with Dash

A general requirement while working with javascript is to process strings and replace particular characters with some other. One such condition is to replace spaces with the dash in javascript strings.

Table of Contents:-

Javascript string replace spaces with dash using replace()

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

The first argument is the pattern to be searched within the calling string to be replaced, and the second is the substitute.

Example:-

Replace spaces with a dash in the string “Java Script”

Code:-

let dummyString = "Java Script";
dummyString = dummyString.replace(/\s+/g, '-');
console.log(dummyString);

Output:-

Java-Script

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.
  • g specifies to search all the occurrences of the pattern within the string.
  • ‘-‘ is the replacement used to substitute the space.

Javascript string replace spaces with dash using split() and join()

Javascript’s split(separator) method returns an array of substrings formed by splitting a given string. The separator can be a single character, a string or a regular expression.

Javascript’s join(separator) method concatenates all the elements of the string array back into a new string separated by the specified separator value in the argument or comma if nothing is specified.

Example:-

Replace spaces with a dash(-) in the string “Java Script”

Code:-

let dummyString = "Java     Script";
dummyString = dummyString.split(/[\s]+/).join("-");
console.log(dummyString); 

Output:-

Java-Script

Explanation:-

  • The split() method is used to split the string into an array of elements. The division is based on spaces (\s)
  • Note that the separator used in the split() method is a regular expression /[\s]+/ so that this solution will work even if there are multiple spaces.
  • Finally, join all the array elements using the dash (‘-‘) with the help of the  join(‘-‘) method separated by a single space to form a new string.

Read More:

I hope this article helped you to replace space/spaces with the dash in a javascript string. Good Luck!!!

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top