我试图创建一个函数,这个函数应该把句子中的第一个单词大写,它也应该大写缩写字符。
示例:
a.m.a.普通精神病学档案-> A.M.A.普通精神病学档案
a.m.a.神经病学档案-> A.M.A.神经病学档案
a.m.a.神经病学和精神病学档案-> A.M.A.神经病学和精神病学档案
以下是我到目前为止尝试过的:
但到目前为止还没有运气。
function transform(str) {
let smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\'\s-]*/g, function(match, index, title) {
if (index > 0 && index + match.length !== title.length &&
match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
(title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
(title.charAt(index + match.length) !== "'" || title.charAt(index - 1) === "'") &&
title.charAt(index - 1).search(/[^\s-]/) < 0) {
return match.toLowerCase();
}
if (match.substr(1).search(/[A-Z]|\../) > -1) {
return match;
}
return match.charAt(0).toUpperCase() + match.substr(1);
});
}
function showRes(str) {
document.write(transform(str));
}<button onclick="showRes('a.m.a. archives of neurology')">convert</button>
发布于 2016-11-23 08:54:12
我已经完全重写了这个函数:
function transform(str) {
let smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
let words = str.split(' '); // Get me an array of separate words
words = words.map(function(word, index) {
if (index > 0 && ~word.search(smallWords))
return word; // If it's a small word, don't change it.
if (~word.lastIndexOf('.', 1)) // If it contains periods, it's an abbreviation: Uppercase.
return word.toUpperCase(); // lastIndexOf to ignore the last character.
// Capitalize the fist letter if it's not a small word or abbreviation.
return word.charAt(0).toUpperCase() + word.substr(1);
});
return words.join(' ');
}
console.log(transform('a.m.a. archives of neurology'));
console.log(transform('a.m.a. archives of neurology.'));
console.log(transform('a case study. instit. Quar.'));
https://stackoverflow.com/questions/40759674
复制相似问题