Skip to content
Advertisement

Convert slug variable to title text with javascript

I’m trying to do something that would be similar to turning a url slug-like variable into text that could be used for a title.

So, I have a variable for example that is like this:

var thisID = 'athlete-profile';

function myFunc(thisID) {
    // i need to use thisID as the id and href in a loop that generates a string of <li><a>'s

    function makeTitle(thisID) {
        // convert thisID to text so for this example it would return 'Athlete Profile'
        return 'Athlete Profile';
    }

    for () {
        var str = '<li id="'+thisID+'"><a href="#'+thisId+'">'+makeTitle(thisID)+'</a>';
    }
    // make sense?
}

I’d like to not use a regex to do this if possible somehow, but I don’t think there’s a way to do it without one. So any one who knows how to do this type of thing let me know, it would be a great help.

Thanks

Advertisement

Answer

I would advise you to use regular expression. But if you really don’t want to use regular expressions, the solution below would work for simple cases. Feel free to modify it as you like it.

function makeTitle(slug) {
  var words = slug.split('-');

  for (var i = 0; i < words.length; i++) {
    var word = words[i];
    words[i] = word.charAt(0).toUpperCase() + word.slice(1);
  }

  return words.join(' ');
}

console.log(
  makeTitle("athlete-profile")
)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement