如何大写缩写和字符串中的每个第一个单词?

时间:2016-11-23 08:47:27

标签: javascript regex

我正在尝试创建一个函数,该函数应该大写句子中的每个第一个单词+它还应该大写缩写字符。

例:
a.m.a.一般精神病学档案 - > A.M.A.普通精神病学档案

a.m.a。神经病学档案 - > A.M.A.神经病学档案

a.m.a。神经病学和精神病学档案 - > A.M.A.神经病学和精神病学档案

以下是我迄今为止尝试的内容:

但到目前为止还没有运气。



Sub Test()

Dim source As Worksheet, target As Worksheet, rng As Range, col As Integer, account As Range

Set source = ActiveSheet
Set target = Worksheets("Updated")

For Each rng In source.Range("A8:A" & Range("A8").End(xlDown).Row)

    Set account = rng

    For col = 2 To rng.End(xlToRight).Column

        If Cells(rng.Row, col) <> 0 Then

            target.Range("E5").End(xlDown).Offset(1, 0) = Cells(rng.Row, col)
            target.Range("E5").End(xlDown).Offset(0, 1) = account

        End If

    Next col

Next rng

End Sub
&#13;
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));
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

我完全重写了这个功能:

&#13;
&#13;
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.'));
&#13;
&#13;
&#13;