在 javascript 中将连字符的名称大写 [英] Capitalize hyphenated names in javascript

查看:50
本文介绍了在 javascript 中将连字符的名称大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 javascript 中的名称大写,到目前为止我已经在 SO 上找到了这些方法:

I need to capitalize names in javascript and so far I've found these methods on SO:

// doesn't capitalize first letter after hyphen -> gives Bjørn-martin
str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });

// capitalizes after hyphen, but also after funny Norwegian characters (æøå) -> gives BjøRn-Martin
str.replace(/\b[\w']+\b/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });

// same as first
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
    return letter.toUpperCase();
});

当尝试将 bjørn-martin 大写时,它们都不能同时处理有趣的挪威字符和连字符.

When trying to capitalize bjørn-martin none of them handles both funny Norwegian characters and hyphen.

我不太精通正则表达式,想知道是否有人能指出我正确的方向,以便 bjørn-martin 正确地大写为 Bjørn-Martin.

I'm not exactly well versed in regex and was wondering if anyone could point me in the right direction so that bjørn-martin is correctly capitalized to Bjørn-Martin.

推荐答案

这应该适合您的需求:

var capitalized = input.replace(/(^|[\s-])\S/g, function (match) {
    return match.toUpperCase();
});

这篇关于在 javascript 中将连字符的名称大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆