javascript - 在javascript中大写名称

标签 javascript typescript

我有一个将句子大写的函数。但它不能将名称大写,例如,

D'agostino, Fred  
D'agostino, Ralph B.  
D'allonnes, C. Revault  
D'amanda, Christopher 

我期待:

D'Agostino, Fred  
D'Agostino, Ralph B.  
D'Allonnes, C. Revault  
D'Amanda, Christopher 

函数:

getCapitalized(str){
    var 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);
    });
  }

谁能帮我解决这个问题?我试过使用 (title.charAt(index + match.length) !== "'"|| title.charAt(index - 1) === "'") 但它没有帮助。

最佳答案

我不确定您需要处理的所有用例,但对于您提出的问题,您可以使用查找单词边界的正则表达式:

function capitalizeName(name) {
  return name.replace(/\b(\w)/g, s => s.toUpperCase());
}

console.log(capitalizeName(`D'agostino, Fred`));
console.log(capitalizeName(`D'agostino, Ralph B.`));
console.log(capitalizeName(`D'allonnes, C. Revault`));
console.log(capitalizeName(`D'amanda, Christopher`));

关于javascript - 在javascript中大写名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40099093/

相关文章:

angular - typescript /Angular 10 : component with generic union type

javascript - 为什么 JavaScript Date 构造函数在这个数字上失败,但作为方法却可以正常工作

javascript - 当对象中的所有变量都为假时,AngularJs 禁用按钮

javascript - 来自多维数组的全日历事件数据

javascript - 从 API 绑定(bind)数据时 React JS 意外结束 JSON 输入错误

javascript - 如何使用 Jest 模拟直接导入的函数?

html - 我想在点击登录按钮后导航到另一个页面

javascript - 如何正确使用拼接和切片

javascript - Bootstrap 不关闭菜单

Javascript 函数仅在第二次悬停后执行