I wrote myself a function to turn a string into an abbreviation and it's currently fairly long and it's case-sensitive.
I need a way shorten it so it works 100% of the time. Currently it screws up if one of the splitting words has a capital, if a word ends in a splitting word.
My splitting words are basically the words I'm removing (as most companies and such don't include them). They include:
- and
- of
- the
- for
- to
Also, the way I'm removing them is using split and join (str.split('and ').join('')
) which to me doesn't seem like the easiest way.
Other than these issues, it works fine. Could anyone help me shrink the function and fix the issues? Thanks.
Function:
String.prototype.toAbbrev = function () {
var s = [];
var a = this.split('and ').join('').split('of ').join('').split('the').join('').split('for ').join('').split('to ').join('').split(' ');
for (var i = 1; i < a.length + 1; i++) {
s.push(a[i - 1].charAt(0).toUpperCase());
}
return s.join('.');
}
Outputs on Tested Companies
The National Aeronautics and Space Administration -> N.A.S.A The National Roads and Motorists' Association -> N.R.M.A Royal Society for the Prevention of Cruelty to Animals -> R.S.P.C.A
i
modifier to make it case-insensitive.this
parameter which most people do not really understand the rules of nor the (usually) simpler alternatives. Next, you can of course be clobbering other functions. Finally, its got all the same limitations as a global function, the fact that its namespaced to a string doesn't really change the scope mechanism