views:

262

answers:

3

I want to generate an abbreviation string like 'CMS' from the string 'Content Management Systems', preferably with a regex.

Is this possible using JavaScript regex or should I have to go the split-iterate-collect?

+4  A: 

Capture all capital letters following a word boundary (just in case the input is in all caps):

var abbrev = 'INTERNATIONAL Monetary Fund'.match(/\b([A-Z])/g).join('');

alert(abbrev);
Sinan Ünür
I believe the correct way to call it is Javascript and is NOT JavaScript, it is not a scripting language that has anything to do with java. Correct me if I am wrong.
Shrikant Sharat
@sharat87: You are wrong. It was first named LiveScript but was renamed JavaScript to surf on the hype around the new Java language at the time... Look at all authoritative references (Netscape which created it, Mozilla which took the relay), they name it JavaScript.
PhiLho
@sharat87: Wikipedia.org, javascript.com and w3school.com all talk about JavaScript. But really, who cares? I mean, when someone mentions 'Javascript' or 'JavaScript', it's clear they're not talking about Java.
Bart Kiers
@sharat87 See http://www.sun.com/suntrademarks/#J ... Find `JavaScript`.
Sinan Ünür
Damn! I was told that it was first called ECMAScript and then changed to Javascript for marketing purposes..., but I am happy now :D Thanks you guys :)
Shrikant Sharat
+3  A: 
var input = "Content Management System";
var abbr = input.match(/[A-Z]/g).join('');
RaYell
Cool solution, but what if the first characters of the words were not capitals?
Shrikant Sharat
Then you must split the string and pick first letter from each word.
RaYell
+1  A: 

Adapting my answer from Convert string to proper case with javascript (which also provides some test cases):

var toMatch = "hyper text markup language";
var result = toMatch.replace(/(\w)\w*\W*/g, function (_, i) {
    return i.toUpperCase();
  }
)
alert(result);
PhiLho
wow! you could pass a function to replace ?? Could you point me to read more on that :) Thanks
Shrikant Sharat