开发者

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

开发者 https://www.devze.com 2023-03-16 23:56 出处:网络
I have the 开发者_开发知识库following code adapted from a previous question/answer: var str = $(\'title\').text();

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.


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.


You could also use css selector:

.toUpperCase:first-letter { text-transform:uppercase }

and then

<div class="toUpperCase">text</div>

0

精彩评论

暂无评论...
验证码 换一张
取 消