7

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?

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
sharat87
  • 7,330
  • 12
  • 55
  • 80

6 Answers6

21

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
  • 116,958
  • 15
  • 196
  • 339
9
var input = "Content Management System";
var abbr = input.match(/[A-Z]/g).join('');
RaYell
  • 69,610
  • 20
  • 126
  • 152
5

Note that examples above will work only with characters of English alphabet. Here is more universal example

const example1 = 'Some Fancy Name'; // SFN
const example2 = 'lower case letters example'; // LCLE
const example3 = 'Example :with ,,\'$ symbols'; // EWS
const example4 = 'With numbers 2020'; // WN2020 - don't know if it's usefull
const example5 = 'Просто Забавное Название'; // ПЗН
const example6 = { invalid: 'example' }; // ''

const examples = [example1, example2, example3, example4, example5, example6];
examples.forEach(logAbbreviation);

function logAbbreviation(text, i){
  console.log(i + 1, ' : ', getAbbreviation(text));
}

function getAbbreviation(text) {
  if (typeof text != 'string' || !text) {
    return '';
  }
  const acronym = text
    .match(/[\p{Alpha}\p{Nd}]+/gu)
    .reduce((previous, next) => previous + ((+next === 0 || parseInt(next)) ? parseInt(next): next[0] || ''), '')
    .toUpperCase()
  return acronym;
}
Anynomius
  • 211
  • 2
  • 4
2

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);
Community
  • 1
  • 1
PhiLho
  • 40,535
  • 6
  • 96
  • 134
0

Based on top answer but works with lowercase and numbers too

const abbr = str => str.match(/\b([A-Za-z0-9])/g).join('').toUpperCase()
const result = abbr('i Have 900 pounds')
console.log(result)
danday74
  • 52,471
  • 49
  • 232
  • 283
0

'your String '.match(/\b([a-zA-Z])/g).join('').toUpperCase();

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 20 '22 at 01:37