2

我想在获得空格时将字符串的字符大写,但不更改其他字母。例如。

the mango tree -> The Mango Tree
an elephant gone -> An Elephant Gone
the xyz hotel -> The Xyz Hotel

在javascript中

4

2 回答 2

2

由于您没有指定为什么需要这样做,我想猜测它主要用于文本显示。如果是这种情况,您可能想要一个更简单的 CSS 解决方案:text-transform:capitalize- 让浏览器完成工作!

除此之外,似乎在此之前已经回答了这个问题:Convert string to title case with JavaScript

于 2012-06-06T13:30:23.723 回答
2

您可以执行以下操作:

var capitalize = function (text)
{
    return text.replace(/\w\S*/g, function (text) { 
        return text[0].toUpperCase() + text.substring(1);
    });
}

alert(capitalize('the dog ran fast'));

与其他建议不同,这将允许您在字符串中保留其他大写字母。例如,字符串“我的变量名是coolCat”会变成“我的变量名是CoolCat”。

于 2012-06-06T13:37:26.233 回答