Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery uppercase first letter of title with some exceptions?

Tags:

jquery

I have the following code adapted from a previous question/answer:

var str = $('title').text();
str = str.toLowerCase().replace(/\b[a-z]/g, convert);
       function convert(){
 return arguments[0].toUpperCase();
       }
 $('title').text(str);

I need to add some exceptions to this such as 'and'.

Thanks in advance.

like image 957
Paul Avatar asked Jul 04 '11 14:07

Paul


1 Answers

You could build an Array of the exceptions and check to see if the matched string matches.

If so, just return it as is.

var str = document.title,
   exceptions = ['hello', 'and', 'etc'];

str = str.toLowerCase().replace(/\b([a-z])\w*\b/g, convert);

function convert(word, firstChar) {
    if ($.inArray(word, exceptions) != -1) {
        return word;
    }
    return firstChar.toUpperCase() + word.substr(1);
}

document.title = str;

jsFiddle.

like image 174
alex Avatar answered Nov 10 '22 21:11

alex