Create a Titleize Method, That Excludes "Little Words"

Create a titleize method, that excludes little words.

arr = ['a', 'an', 'the']
str ="This is a salil gaikwad working as an engineer"
str.gsub(/\w+/) {|match| arr.include?(match) ? match : match.capitalize}
#Gives o/p :- This Is a Salil Gaikwad Working As an Engineer

Using title case with Ruby 1.8.7

You could create a list of the word you don't want to capitalize and do

excluded_words = %w(the and in) #etc

def capitalize_all(sentence, excluded_words)
sentence.gsub(/\w+/) do |word|
excluded_words.include?(word) ? word : word.capitalize
end
end

By the way, if you were using Rails and did not need to exclude specific words you could use titleize.

"the catcher in the rye".titleize
#=> "The Catcher In The Rye"

Capitalizing titles

Building off of Josh Voigts comment:

def titleize(name)
lowercase_words = %w{a an the and but or for nor of}
name.split.each_with_index.map{|x, index| lowercase_words.include?(x) && index > 0 ? x : x.capitalize }.join(" ")
end

You might want make lowercase_words a constant and move it out of the function since they won't ever change.

Manual Titleize in Ruby 2.3.3

You have a string literal in condition warning in:

if i == "of" || "the" || "and"

You're trying to compare i with of or the or and, but after the first try, you're not passing a left value to compare, try with:

if i == "of" || i == "the" || i == "and"

More idiomatic Ruby would be to use include?

if ['of', 'the', 'and'].include?(i)

This way at least you get Jaws

The reason because your actual method doesn't work for the string war and peace is because if the length of the word being passed is minor or equal than 2 then it'll execute next, so, it'll only capitalize the word peace.

How to Capitalize text_field Words in Real Time Excluding Prepositions?

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(' ');
}

Modifying an array item in Ruby if it includes a specific word

I like to break these types of problems up into smaller chunks of logic to help me understand before I write an algorithm. In this case you need to modify each word of the string based on some rules.

  1. If it's the first word, capitalize it.
  2. If it's not a special word, capitalize it.
  3. If it's a special word AND it's not the first word, downcase it.

With these rules you can write your logic to follow.

special_words = ['a', 'an', 'and', 'of', 'the']
fixed_words = []
@string.downcase.split.each_with_index do |word, index|
# If this isn't the first word, and it's special, use downcase
if index > 0 and special_words.include?(word)
fixed_words << word
# It's either the first word, or not special, so capitalize
else
fixed_words << word.capitalize
end
end
fixed_words.join(" ")

You'll notice I'm using downcase on the string before calling split and each_with_index. This is so that all the words get normalized a downcase and can be easily checked against the special_words array.

I'm also storing these transformed words in an array and joining them back together in the end. The reason for that, is if I try to use downcase! or capitalize! on the split strings, I'm not modifying the original title string.

Note: This problem is part of the Bloc Full Stack course work which is why I'm using a simplified solution, rather than one liners, modules, file io, etc.

Convert camelCaseText to Title Case Text

const text = 'helloThereMister';
const result = text.replace(/([A-Z])/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);


Related Topics



Leave a reply



Submit