Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert slug variable to title text with javascript

Tags:

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

like image 974
jaredwilli Avatar asked Jan 24 '12 01:01

jaredwilli


2 Answers

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")
)
like image 183
Moon Avatar answered Sep 20 '22 19:09

Moon


function titleize(slug) {
  var words = slug.split("-");
  return words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
  }).join(' ');
}

console.log(titleize("athlete-profile"))

It works pretty simply:

  • It splits the string by - into words.
  • It maps each word into title case.
  • It joins the resulting words with spaces.
like image 44
icktoofay Avatar answered Sep 21 '22 19:09

icktoofay