I've got a title
string that comes in from a form my users will submit. I'd like to take that title
, in whatever way it is written, and format it to title case, which I believe to be the most read-friendly way.
alexis Sanchez -> Alexis Sanchez
sanchez's ball -> Sanchez's Ball
sanchez and co -> Sanchez and Co
I'd also like to take words like "and" or "or" and have them as lowercase, just as shown above. Is this possible?
Also, on some occasions, I'd like to take this title
and filter it so it ignores any special characters like apostrophes and separates it with dashes. This will be for URLs (i.e. .com/sanchezs-ball
).
alexis Sanchez -> alexis-sanchez
ALEXIS Sanchez -> alexis-sanchez
sanchez's ball -> sanchezs-ball
I've created two functions that do almost this. I just need some advice in how to tweak them to get them to my desired format.
This one takes my title
and turns it into a URL-likeable string. Can this be improved/shortened?
function hashifyString(dirtyString) {
var title = dirtyString
.replace(/[^a-z0-9\s]/gi, '')
.replace(/\b\w+/g,function(s){return s.substr(0).toLowerCase();})
.replace(/[_\s]/g, '-');
return title;
}
I need some advice on how to improve upon this one, so it looks out for "and" or "or" and keeps these two words lowercase while keeping the rest of the string title case?
function beautifyString(dirtyString) {
var string = dirtyString
.replace(/[^a-z0-9\s]/gi, '')
.replace(/\b\w+/g,function(s){return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();})
return string;
}
I hope this makes sense. Any help is appreciated. Thanks in advance!