我想从字符串'Content Management Systems'生成一个缩写字符串,如'CMS',最好使用正则表达式.
这可能是使用JavaScript正则表达式,还是我必须进行split-iterate-collect?
Sin*_*nür 13
捕获字边界后的所有大写字母(以防输入全部大写):
var abbrev = 'INTERNATIONAL Monetary Fund'.match(/\b([A-Z])/g).join('');
alert(abbrev);
Run Code Online (Sandbox Code Playgroud)
var input = "Content Management System";
var abbr = input.match(/[A-Z]/g).join('');
Run Code Online (Sandbox Code Playgroud)
请注意,上面的示例仅适用于英文字母字符。这是更普遍的例子
\nconst example1 = \'Some Fancy Name\'; // SFN\nconst example2 = \'lower case letters example\'; // LCLE\nconst example3 = \'Example :with ,,\\\'$ symbols\'; // EWS\nconst example4 = \'With numbers 2020\'; // WN2020 - don\'t know if it\'s usefull\nconst example5 = \'\xd0\x9f\xd1\x80\xd0\xbe\xd1\x81\xd1\x82\xd0\xbe \xd0\x97\xd0\xb0\xd0\xb1\xd0\xb0\xd0\xb2\xd0\xbd\xd0\xbe\xd0\xb5 \xd0\x9d\xd0\xb0\xd0\xb7\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xb8\xd0\xb5\'; // \xd0\x9f\xd0\x97\xd0\x9d\nconst example6 = { invalid: \'example\' }; // \'\'\n\nconst examples = [example1, example2, example3, example4, example5, example6];\nexamples.forEach(logAbbreviation);\n\nfunction logAbbreviation(text, i){\n console.log(i + 1, \' : \', getAbbreviation(text));\n}\n\nfunction getAbbreviation(text) {\n if (typeof text != \'string\' || !text) {\n return \'\';\n }\n const acronym = text\n .match(/[\\p{Alpha}\\p{Nd}]+/gu)\n .reduce((previous, next) => previous + ((+next === 0 || parseInt(next)) ? parseInt(next): next[0] || \'\'), \'\')\n .toUpperCase()\n return acronym;\n}Run Code Online (Sandbox Code Playgroud)\r\n