10

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

3
  • What is that for loop doing? Element ids need to be unique, so you shouldn't be creating elements in a loop and giving them all the same id. Commented Jan 24, 2012 at 1:03
  • no, thisID is always a different id, and actually, i meant to make it <li class="'thisID" the for loop is negligible. I really am just worried about the makeTitle() function and returning the var but without hyphens. I can use CSS to capitalize the text then. Commented Jan 24, 2012 at 1:06
  • If you just want to change hyphens to spaces it is super simple: thisID.replace(/-/g, " ") (as shown in the first part of my answer). But doing the capitalisation is also easy as shown in any of the answers below. Commented Jan 24, 2012 at 1:42

9 Answers 9

16

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") )

Sign up to request clarification or add additional context in comments.

4 Comments

What makes you advise using regular expressions for this?
@icktoofay: Please refer to stackoverflow.com/questions/6243563/regex-vs-while-loops ... And, in this particular case, regex is not too complicated as well.
@icktoofay - I'd advise regular expressions for this for two reasons. Firstly it's a really easy solution. Secondly, one way to express the requirement in plain English is that the OP wants to replace hyphens with spaces, and replace first letter lowercase with uppercase, so to me it seems only logical to go ahead and use the .replace() method to achieve that. Obviously there are other ways to do it, and the .split() and .join() method from your answer (or this one) is quite neat too.
I meant to get back to you on this a while ago, i realized that i could just use the split() method to split it at the - and then concat the 2 array keys back together. I didn't use this exact answer, since CSS can do the capitalizing stuff, but the general idea was right, had i seen it first before remembering it was doable with split().
10

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.

2 Comments

Note that this requires Array.prototype.map. Some older browsers do not support it. If this is a problem, you can shim it or use jQuery's $.map or underscore.js's _.map or some other library's equivalent function instead.
The MDN page you linked to has a stand-alone implementation of .map() if the OP doesn't want to include an entire library.
4

The makeTitle() part of your question can be implemented something like this:

function makeTitle(thisID) { return thisID.replace(/-/g, " ").replace(/\b[a-z]/g, function() { return arguments[0].toUpperCase(); }); } console.log(makeTitle("athlete-profile"))

The first .replace() changes all hyphens to spaces, and then the second .replace() takes any lower-case letter that follows a word boundary and makes it upper-case.

(For more information see the MDN doco for .replace().)

As far as doing it without using regular expressions, I'm not sure why you'd specifically want to avoid them, especially when the required expressions are pretty simple in this case (especially if you do the hyphen to space and first letter capitalisation in two steps as shown above). But there are endless ways to do this without regex using various combinations of JavaScript's string manipulation methods.

Comments

3

Do it in one line:

'athlete-profile'.split("-").join(" ").replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()}) 

Output: Athlete Profile

Comments

0

Do it like this

 let someString = 'im a string'; console.log(someString.replace(/-/g, ' ') .replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() }) ) 

Output: Im A String

Comments

0

Short and great way:

const slugToText = (slug) => { return slug.toLowerCase().replace(/-/g,' ') } 

Comments

0

Much Simplified answer

we can use String.prototype.replaceAll method to easily achieve this

function convertSlugToString(slug) { return slug.replaceAll("-", " "); } 

incase you want to make sure the output is all lowercase then you can do the following

function convertSlugToString(slug) { return slug.toLowerCase().replaceAll("-", " "); } 

Additional info:

String.prototype.replaceAll() is a ES2021 feature and it also has a great browser support with 93.64% global coverage, click here for more info

if you want to support IE then refer to the other answers

Comments

0

Here's a one liner ready to add to your app helpers:

/** * Converts slug to title * * @example * toTitle('slug-word') */ const toTitle = (slug) => slug.toLowerCase().split(/[-_.\s]/).map((w) => `${w.charAt(0).toUpperCase()}${w.substr(1)}`).join(' '); 

Example:

toTitle('one-two_three.four Five') >> 'One Two Three Four Five' 

2 Comments

Nice, but sadly lowercases all acronyms such as BBC to Bbc :(
You can omit the .toLowerCase() call to maintain uppercasing.
-1
//this is wrong : function convertSlugToString(slug) { return slug.toLowerCase().replaceAll("-", " "); } //is the reverse form for work well: function convertSlugToString(slug) { return slug.toLowerCase().replaceAll(" ", "-"); } 

1 Comment

The poster wanted to convert the dashes to spaces, not the spaces to dashes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.