我希望能够使用正则表达式从字符串“Content Management Systems”生成类似于“CMS”的缩写字符串。这是否可以在JavaScript中使用正则表达式实现,还是需要拆分-迭代-收集的方法呢?
捕获所有跟随单词边界的大写字母(以防输入全是大写字母):
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('');
请注意,上述示例仅适用于英文字母。下面是一个更为通用的示例:
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;
}
我从用JavaScript将字符串转换为正确的大小写中借鉴了一些答案,并提供了一些测试用例:
var toMatch = "hyper text markup language";
var result = toMatch.replace(/(\w)\w*\W*/g, function (_, i) {
return i.toUpperCase();
}
)
alert(result);
基于顶部答案,但也适用于小写字母和数字
const abbr = str => str.match(/\b([A-Za-z0-9])/g).join('').toUpperCase()
const result = abbr('i Have 900 pounds')
console.log(result)
'your String '.match(/\b([a-zA-Z])/g).join('').toUpperCase();
可以将字符串中的所有单词首字母变成大写。