Generate an abbreviation from a string in JavaScript using regular expressions?
Asked Answered
S

6

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?

Symbolics answered 2/10, 2009 at 7:29 Comment(0)
Y
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);
Ysabel answered 2/10, 2009 at 7:35 Comment(0)
F
9
var input = "Content Management System";
var abbr = input.match(/[A-Z]/g).join('');
Faludi answered 2/10, 2009 at 7:36 Comment(2)
Cool solution, but what if the first characters of the words were not capitals?Symbolics
Then you must split the string and pick first letter from each word.Faludi
D
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;
}
Davila answered 28/11, 2020 at 20:41 Comment(0)
B
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);
Bentwood answered 2/10, 2009 at 9:2 Comment(1)
wow! you could pass a function to replace ?? Could you point me to read more on that :) ThanksSymbolics
H
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)
Hsu answered 22/11, 2021 at 18:29 Comment(0)
C
0

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

Constantine answered 17/10, 2022 at 15:17 Comment(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.Oeillade

© 2022 - 2024 — McMap. All rights reserved.