I have a Dynamic Breadcrumb set up with JavaScript. All I want is to do Initial Caps for each word.
Example: Home > Some > Page
Currently I have them all converted to lowercase and have removed all - from the strings in pages that have multiple words. I just need to convert the string to Initial Caps. Here is my code that I have working so far:
var path = "",
href = document.location.href,
domain = href.match(/:\/\/(.[^/]+)/)[1],
replacedomain = 'http://' + domain + '/',
s = href.replace(/-/gi, " ").split("/"),
lastElement = document.location.href.split('/').splice(-1,1);
for (var i = 2; i < (s.length - 1); i++) {
path += "<a class='bc' href=\"" + href.substring(0, href.indexOf("/" + s[i]) + s[i].length + 1) + "/\">" + s[i] + "</a> > ";
if (i > 0) {
breadcrumb = path;
}
}
i = s.length - 1;
breadcrumb += "<span>" + s[i] + "</span>";
var breadcrumbl = breadcrumb.toLowerCase(),
domain = breadcrumbl.match(/:\/\/(.[^/]+)/)[1],
breadcrumb2 = breadcrumbl.replace(domain, "").replace(domain, ""),
breadcrumbs = breadcrumb2,
url = '<a href="/">Home</a>' + breadcrumbs;
document.getElementById('breadcrumb1').innerHTML=url;
I think the solution is with a regular expression but I'm not good at writing them and I'm having a hard time with the concept. Also if anyone thinks this script can be optimized further your feedback is welcome. I'll will make variable names more semantic for production.
I recently wrote this helper method to do this for me:
function autocase ( text ) {
return text.replace(/(&)?([a-z])([a-z]{2,})(;)?/ig,function ( all, prefix, letter, word, suffix ) {
if (prefix && suffix) {
return all;
}
return letter.toUpperCase() + word.toLowerCase();
});
}
It takes into account things such as ™
Edit: To use this method, simply pass it a string, and it will return the string auto cased. It does not work on html strings.
//...
document.getElementById('breadcrumb1').innerHTML=url;
function autocase ( text ) {
return text.replace(/(&)?([a-z])([a-z]{2,})(;)?/ig,function ( all, prefix, letter, word, suffix ) {
if (prefix && suffix) {
return all;
}
return letter.toUpperCase() + word.toLowerCase();
});
}
$("#breadcrumb1 a").text(function(i,text){
return autoCase(text);
});
Try using css property text-transform:capitalize;
for the breadcrumb.
Mostlikely in you case it should be,
.breadcrumb1 a {
text-transform: capitalize;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With