Why can't .replace(' ','-') replace all the spaces in the string

Why can't .replace(' ','-') replace all the spaces in the string


function spinalCase(str) {

str = str.replace(’ ‘,’-’);
return str;
spinalCase(‘This Is Spinal Tap’);

This-Is Spinal Tap


The first argument of replace() is a regex. If you send it just a string, it just defaults to doing the first occurrence. If you want it to do them all, you need to use a regex so you can use the global flag. For example, if you wanted to replace all of the ‘p’ with a ‘w’, it would be

str = str.replace(/p/g,'w');


MDN says it’s either:

str.replace(regexp|substr, newSubstr|function)

and also:

substr (pattern)
A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.


Because .replace() replaces the first match only.
The syntax is String.replace(regexp|substr, newSubstr|function).
Since you are replacing many spaces, it’s best to use regex.

like this:
function spinalCase(str) {
  let space = /\s/g;
  str = str.replace(space,'-');
  return str;

spinalCase('This Is Spinal Tap');

This will hyphenate the whole thing.
This challenge is much more complicated though. You must spinal case all of these examples:

spinalCase(“This Is Spinal Tap”)); // should return “this-is-spinal-tap”.
spinalCase(“thisIsSpinalTap”)); // should return “this-is-spinal-tap”.
spinalCase(“The_Andy_Griffith_Show”)); // should return “the-andy-griffith-show”.
spinalCase(“Teletubbies say Eh-oh”)); // should return “teletubbies-say-eh-oh”.
spinalCase(“AllThe-small Things”)); //

Good luck!


If you want to get a good undestanding for regular expressions check out this playground: