AnthonyGalli.com AnthonyGalli.com - 5 months ago 18
Ruby Question

How to Capitalize text_field Words in Real Time Excluding Prepositions?

How to titleize/captialize words, like this website, so that prepositions aren't included?

I'm not looking for you to list all the prepositions, but if you can just show how it can be done with a few like, "of, on, and" I would greatly appreciate it.

<%= f.text_area :name, id: "challenge-name" %>

<script> # This code capitalizes ALL words
function makeTitle(slug) {
var words = slug.split(' ');

$.each(words, function(index, word){
words[index] = word.charAt(0).toUpperCase() + word.slice(1);
});

return words.join(' ');
}

$('#challenge-name').on('keyup', function(){ $(this).val( makeTitle($(this).val())) })
</script>


UPDATE BASED ON FRED's ANSWER



function makeTitle(slug) {
var preps = ['and', 'a', 'of', 'but', 'from'];
return $.map(slug.split(' '), function(k, v) {
return $.inArray(k.match(/\w*/g)[0], preps) >= 0 ? k : k[0].toUpperCase() + k.slice(1);
}).join(' ');
}

$('#challenge-name').on('keyup', function(){ $(this).val( makeTitle($(this).val())) })

Answer

You might want to watch out for punctuation - this code takes punctuation into account:

def makeTitle(slug)
  preps = ['and', 'a']
  str.split(' ').map do |w| 
    preps.include?(/\w*/.match(w)[0]) ? w : w.capitalize 
  end.join ' '
end

I'll blame the late hour last nite - I didn't realize the OP wanted a jquery/javascript solution, so I created one in Ruby. I'll leave that in place in case any future viewer is looking for an answer in Ruby, but here is a JS method (using jQuery):

function makeTitle(slug) {
  var preps = ['and', 'a'];
  return $.map(slug.split(' '), function(k, v) {
    if(k){
        var word = k.match(/\w*/g)[0].toLowerCase();
      var letter = $.inArray(word, preps) >= 0 ? k[0].toLowerCase() : k[0].toUpperCase();
        return letter + k.slice(1);
    } else {
      return k;
    }
  }).join(' ');
}
Comments