我想創建一個函數,應該大寫句子中的每個第一個單詞+它也應該大寫縮寫字符。如何大寫縮寫和字符串中的每個第一個單詞?
例如:
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>
@downvoter - 護理指定有效的理由! – Rayon
按空格拆分字符串,按點分割這些字符串,然後用大寫字母替換index [0]處的每個字母。不需要正則表達式。 – Seth