nasty
nasty

Reputation: 7087

jQuery capitalize everything except the word and

This is my menu with all in Capitals

<ul class="tabgic">
   <li rel="item_227" class="">
    <div>
      <div> <a class="menu_link_2" href="#">ACCIDENTAL DAMAGE AND PROPERTY</a> </div>
    </div>
   </li> 
</ul>

I want to use jQuery and Capitalise everything except the word and so the output will be

Accidental Damage and Property

How can I do this?

I was looking at this but not sure if this can be modified easilly?

Upvotes: 0

Views: 142

Answers (4)

Tats_innit
Tats_innit

Reputation: 34117

Working Demo http://jsfiddle.net/pXe44/

Hope it fits the cause :)

code

$(document).ready(function() {
    var foo = $('.menu_link_2').text().split(' ');
    var html = '';
    $.each(foo, function() {
        if (this.toLowerCase() != "and") html += this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase() + ' ';
        else html += this.toLowerCase() + ' ';

    });

    alert(" ===> " + html);

    $('.menu_link_2').html(html);

});​

Upvotes: 0

pete
pete

Reputation: 25091

Given your proposed output, I suspect you actually want Title Case (also called Proper Case). You could use the linked plugin (it handles Title Case), or you could roll your own using a regex:

// the RegExp  \w{4,}  will capture any word composed of 4 or more characters
// where each character can match A-Z, a-z, 0-9, and _
myString = myString.toLowerCase().replace(/\w{4,}/g, function (match) {
    return match.substring(0, 1).toUpperCase() + match.substring(1);
});

Upvotes: 0

elclanrs
elclanrs

Reputation: 94131

var str = 'ACCIDENTAL DAMAGE AND PROPERTY';
var result = str.split(' ').map(function(v){
  v = v.toLowerCase();
  return v.replace(/^[a-z]/, function(a){
    return v === 'and' ? a : a.toUpperCase();
  });
}).join(' ');

console.log(result); //=> Accidental Damage and Property

Upvotes: 0

alex
alex

Reputation: 490597

You could use a regex.

str = str.toLowerCase().replace(/\b[a-z]/g, function(match) {
    return match.toUpperCase();
}).replace(/\bAnd\b/g, "and");

jsFiddle.

You can't do it with CSS alone (not with the markup you currently have at least).

jsFiddle.

Upvotes: 4

Related Questions