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
  • 115,191
  • 15
  • 191
  • 333
sharat87
  • 7,132
  • 11
  • 50
  • 78

5 Answers5

20

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
  • 115,191
  • 15
  • 191
  • 333
9
var input = "Content Management System";
var abbr = input.match(/[A-Z]/g).join('');
RaYell
  • 68,096
  • 20
  • 124
  • 150
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
  • 171
  • 1
  • 3
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
  • 39,674
  • 6
  • 93
  • 131
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
  • 45,909
  • 39
  • 198
  • 245