简体   繁体   中英

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

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?

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);
var input = "Content Management System";
var abbr = input.match(/[A-Z]/g).join('');

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; }

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);

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM