I created a function for turning strings into abbreviations, but it's currently quite lengthy and case-sensitive.
I'm looking for a way to streamline it so that it functions flawlessly all the time. Right now, it messes up if a splitting word is capitalized or if a word ends with a splitting word.
The words I'm using as splitting words are essentially the ones I want to remove (as most companies don't include them). These words include:
- and
- of
- the
- for
- to
Additionally, my current method of removing them involves using split and join (str.split('and ').join('')
) which I believe may not be the most efficient approach.
Overall, aside from these issues, the function works well. Can anyone assist me in simplifying the function and addressing the problems? Thank you.
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('.');
}
Results 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