5

This is the title of my page:

<title>john smith - Site and site - jobs</title>

I have to capitalize the title of the page until the first hifen (-). This is my code, but lost the second part and the first hyphen.

function toTitleCase(str){
    var str  = document.title;
    subTitle = str.split('-')[0];
    return str.substring(0,str.indexOf('-')).replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substring(1);
    });
}
document.title = toTitleCase(document.title);
pimvdb
  • 151,816
  • 78
  • 307
  • 352
roybatty
  • 191
  • 3
  • 13
  • 1
    Why passing the _str_ parameter to the function if you overwrite it in line 1 of your function anyway? – Chris Jul 06 '12 at 11:08
  • 1
    @roybatty What is correct output for you-> `JOHN SMITH`,or `John Smith`? What do you mean by '`capitalize`'? – Engineer Jul 06 '12 at 11:15
  • Capitalise ordinarily means the first letter, not all, which is the understanding I've based my answer on so I hope this is what he meant – Mitya Jul 06 '12 at 11:19

6 Answers6

1
function toTitleCase(str){
    str = str.split('-');
    str[0]=str[0].replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    return str.join("-");
    }
document.title = toTitleCase(document.title);
1

Always good to throw in a nuclear REGEX route...

var str = "some words - are - here";
console.log("this is - a - string".replace(/^[^\-]*/, function($0) {
    return $0.replace(/\b[a-z]/g, function($0) { return $0.toUpperCase(); });
}));

Outputs:

"Some Words - are - here"
Mitya
  • 33,629
  • 9
  • 60
  • 107
0

Summarizing answers "best of" + my grain of salt :

String.prototype.capitalize = function () {
  return this.replace(/\b[a-z]/g, function ($0) { return $0.toUpperCase(); });
};

function capitalizeTitle()
{
  document.title = document.title.replace(/^[^\-]*/, function($0) {
    return $0.capitalize();
  });
}

capitalizeTitle();
Maxime Pacary
  • 22,336
  • 11
  • 85
  • 113
0

This code will help you.

function toTitleCase(str) {
        subTitle = str.split('-')[0].capitalize();
        return subTitle + str.substring(subTitle.length);
    }

    String.prototype.capitalize = function () {
        return this.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
    }
Jitendra Pancholi
  • 7,897
  • 12
  • 51
  • 84
0

Hey try this please: http://jsfiddle.net/LK3Vd/

lemme know if I missed anything.

Hope this helps :)

code

var str = $('#foo').html();
str = str.substring(0, str.indexOf('-'));

str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
0

This might help..

function ok()
{
  var str  = document.title;
  document.title=str.substring(0, str.indexOf('-')).toUpperCase()+str.substring(str.indexOf('-'),str.length);

}

meteor
  • 2,518
  • 4
  • 38
  • 52