jQuery: Make strings with varying capitalization Title case

css, jquery, string

Solution

you can make this function

function capitalizeMe(val){
    return val.charAt(0).toUpperCase()+val.substr(1).toLowerCase();
}

oh, and maybe you need to remove you css h2 rule

you can apply it to your h2 like this

$('h2').each(function(){
    var str = capitalizeMe($(this).html());
    $(this).html(str);  
});


function replaceAll( text, v1, v2 ){
  while (text.toString().indexOf(v1) != -1)
      text = text.toString().replace(v1,v2);
  return text;
}

if you want to capitalize each instance of "i" you could do something like this

$('h2').each(function(){
    var str = replaceAll(capitalizeMe($(this).html())," i "," I ");
    $(this).html(str);  
});

Problem

Pretty simple question, but I can't quite seem to find the answer. I have several HTML pages from differing sources that have strings in their `<h2>` elements with dumb capitalizations. Such as: `<h2>Are there OTHER USES for this medicine?</h2>` I'm looking to make these regular sentence case, i.e., `<h2>Are there other uses for this medicine?</h2>` I began by making them all lower case with CSS: ``` h2 { text-transform: lowercase; } ``` because I was hoping to then manipulate them with jQuery by making a function that just capitalizes the first letter. So the question is: How would I write a jQuery function to capitalize just the first letter of each `h2` element on a page? After reading this thread, tried this: ``` function capitaliseFirstLetter(string){ return string.charAt(0).toUpperCase() + string.slice(1); } $('h2').each(function(){ capitaliseFirstLetter($(this).text()); }); ``` But it didn't work, and the console didn't give me any errors, so I don't know what's wrong. EDIT I made one large oversight in this question. Using `text-transform: lowercase` made the word I lowercase, so `<h2>What should I do in case of OVERDOSE?</h2>` became `<h2>What should i do in case of overdose?</h2>` when I used @marcelo-biffara's solution. (Or the `:first-letter` CSS syntax.) Now, do I need to use a complicated regexp to just capitalize the string " i "? EDIT 2 If there are two occurrences of " i " (such as in "What should i do if i take too many doses?"), do I need a loop to replace them with " I "?

Original source

Related problems