Vicky Gonsalves Vicky Gonsalves - 17 days ago 5
Javascript Question

How to Capitalize Abbreviations and each first word in string?

I am trying to create a function which should capitalize each first word in the sentence + it should also capitalize the abbreviated characters.

Example:

a.m.a. archives of general psychiatry -> A.M.A. Archives of General Psychiatry

a.m.a. archives of neurology -> A.M.A. Archives of Neurology

a.m.a. archives of neurology and psychiatry -> A.M.A. Archives of Neurology and Psychiatry

Here is whats I have tried so far:

But no luck so far.



function transform(str) {
let smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\'\s-]*/g, function(match, index, title) {
if (index > 0 && index + match.length !== title.length &&
match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
(title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
(title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'") &&
title.charAt(index - 1).search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (match.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
}

function showRes(str) {
document.write(transform(str));
}

<button onclick="showRes('a.m.a. archives of neurology')">convert</button>




Answer

I've completely re-written the function:

function transform(str) {
  let smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
  let words = str.split(' ');      // Get me an array of separate words

  words = words.map(function(word, index) {
    if (index > 0 && ~word.search(smallWords))
      return word;                 // If it's a small word, don't change it.
    
    if (~word.lastIndexOf('.', 1)) // If it contains periods, it's an abbreviation: Uppercase.
      return word.toUpperCase();   // lastIndexOf to ignore the last character.

    // Capitalize the fist letter if it's not a small word or abbreviation.
    return word.charAt(0).toUpperCase() + word.substr(1); 
  });
  
  return words.join(' ');
}

console.log(transform('a.m.a. archives of neurology'));
console.log(transform('a.m.a. archives of neurology.'));
console.log(transform('a case study. instit. Quar.'));