在JavaScript中使用正则表达式从字符串生成缩写?

7
我希望能够使用正则表达式从字符串“Content Management Systems”生成类似于“CMS”的缩写字符串。这是否可以在JavaScript中使用正则表达式实现,还是需要拆分-迭代-收集的方法呢?
6个回答

21

捕获所有跟随单词边界的大写字母(以防输入全是大写字母):

var abbrev = 'INTERNATIONAL Monetary Fund'.match(/\b([A-Z])/g).join('');

alert(abbrev);

9
var input = "Content Management System";
var abbr = input.match(/[A-Z]/g).join('');

很酷的解决方案,但如果单词的首字母不是大写字母呢? - sharat87
然后,您必须拆分字符串并从每个单词中选择第一个字母。 - RaYell

5

请注意,上述示例仅适用于英文字母。下面是一个更为通用的示例:

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


2

我从用JavaScript将字符串转换为正确的大小写中借鉴了一些答案,并提供了一些测试用例:

var toMatch = "hyper text markup language";
var result = toMatch.replace(/(\w)\w*\W*/g, function (_, i) {
    return i.toUpperCase();
  }
)
alert(result);

哇!你可以传递一个函数来替换 ?? 你能指点我去哪里了解更多吗 :) 谢谢 - sharat87

0

基于顶部答案,但也适用于小写字母和数字

const abbr = str => str.match(/\b([A-Za-z0-9])/g).join('').toUpperCase()
const result = abbr('i Have 900 pounds')
console.log(result)


0

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

可以将字符串中的所有单词首字母变成大写。

1
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接