Convert a title cased string into a URL string with dashes? With special characters removed?

suparman21 asked this question 8 months ago
suparman21 on Jan 29

I need to take a string that looks similar to this:

"Function that takes any string and returns it with the 1st character as upper-case?"

And convert it into the following:


This is a string that will be used in the URL for my webpages. And needs to have all the special characters removed and each space needs to be replaced with a dash.

How can I do this in JavaScript?

2 suggested answers
rusty1_rusty1 on Feb 10

Here's a function you can use:

const createQuestionUrlTitle = function(title) {
  title = title.trim() // remove any leading or trailing spaces
  title = title.replace(/\W+/g, '-') // replace each space and special character with a dash
  title = title.toLowerCase() // convert entire string to all lower case

  // make sure first and last characters in a string are not a dash. If so, delete them
  if (title[0] === "-") title = title.substring(1) // first character
  if (title[title.length - 1] === "-") title = title.replace(/.$/,"") // last character

  return title

You can call it like this:

createQuestionUrlTitle("Function that * takes any string / and returns * it with the 1st $ character as upper-case?")

// returns "function-that-takes-any-string-and-returns-it-with-the-1st-character-as-upper-case"
0 replies
nick on Feb 10
string.replace(/\W+/g, '-')

That regular expression will replace each special character or space in your string with a dash (-).

0 replies