Convert Strings using String.Prototype.Replace Method

Please Help. I am trying to replace all whitespace characters with a “-” character.

// The global variable
var globalTitle = "Winter Is Coming";

function urlSlug(title) {

    var re = /[\s]/g
    var replace = /\-/g
    title = title.replace(re, replace)

    return title

var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"

console outputs: Winter/-/gIs/-/gComing

I have been wrapping my head around this for 40 minutes. Does someone see where I made a mistake?

The second argument to replace() should be a string, not a pattern match. The first argument is the pattern match. First argument finds the pattern in the string, second argument replaces that pattern with a new string.

1 Like

thank you bbsmooth.

it really was this simple. I feel pretty dumb now.

Don’t feel dumb. Learning to read documentation is half the battle. It takes a while.