Javascript jQuery 标题大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5086390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:35:26  来源:igfitidea点击:

jQuery Title Case

javascriptjquerystring

提问by AnApprentice

Is there a built in way with jQuery to "title case" a string? So given something like bob smith, it turns into "Bob Smith"?

是否有内置的 jQuery 方法来“标题案例”一个字符串?所以给像鲍勃史密斯这样的东西,它变成了“鲍勃史密斯”?

回答by Ben Blank

You don't need jQuery for this; it can be accomplished using the native .replace()method:

为此,您不需要 jQuery;它可以使用本机.replace()方法完成:

function toTitleCase(str) {
    return str.replace(/(?:^|\s)\w/g, function(match) {
        return match.toUpperCase();
    });
}

alert(toTitleCase("foo bar baz")); // alerts "Foo Bar Baz"

回答by TNC

You can use css, like:

您可以使用 css,例如:

.className 
{
    text-transform:capitalize;
}

This capitalizes the first letter. You can read more here

这将大写第一个字母。你可以在这里阅读更多

回答by Pjotor

In jQuery 1.4+ (at least) you can use

在 jQuery 1.4+(至少)中,您可以使用

var camelized = jQuery.camelCase("some-string");
// Returns "someString"

I could not find it when I last checked the documentation, but it's there and used internally.

我上次检查文档时找不到它,但它在那里并在内部使用。

回答by RBizzle

If you want to combat the terrible people in the world who TYPE IN ALL CAPS, and also title case it at the same time, you can use this variation of the top answer here:

如果您想与世界上所有大写的可怕人物作斗争,并同时将其命名为大写,您可以在此处使用最佳答案的这种变体:

function toTitleCase(str) {
        var lcStr = str.toLowerCase();
        return lcStr.replace(/(?:^|\s)\w/g, function(match) {
            return match.toUpperCase();
        });
    }

alert(toTitleCase("FOO BAR baz")); // alerts "Foo Bar Baz"

回答by Seth

There isn't anything built-in to jQuery that does it, but you can checkout this site that has a basic code example:

jQuery 没有任何内置的东西可以做到这一点,但是您可以查看这个具有基本代码示例的站点:

http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/

http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/

String.prototype.toCamel = function(){
    return this.replace(/(\-[a-z])/g, function(){return .toUpperCase().replace('-','');});
};

It would seem that from there you could call the code like so:

似乎从那里你可以像这样调用代码:

var str = "my string to camel case";
str = str.toCamel();
if ( typeof console !== 'undefined' ) console.log(str);

回答by Ramiro

is way more simple...
You have to use a callback in replace.

更简单......
你必须在替换中使用回调。

toCamelCase = function(str){
  return str.replace(/-\w/g,function(match){return match[1].toUpperCase()})
}
// this works for css properties with "-" 
// -webkit-user-select => WebkitUserSelect

You can change the RegExp to /[-\s]\w/g or /(^|[-\s])\w/g or other...

您可以将 RegExp 更改为 /[- \s]\w/g 或 /(^|[-\s])\w/g 或其他...

回答by Joon

I know this question is a bit old but,

我知道这个问题有点老了,但是,

Here's my version of camelCase function:

这是我的camelCase函数版本:

var camelCase = (function () {
    var DEFAULT_REGEX = /[-_]+(.)?/g;

    function toUpper(match, group1) {
        return group1 ? group1.toUpperCase() : '';
    }
    return function (str, delimiters) {
        return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
    };
})();

It handles all of the following edge cases:

它处理以下所有边缘情况:

  • takes care of both underscores and hyphens by default (configurable with second parameter)
  • string with unicode characters
  • string that ends with hyphens or underscore
  • string that has consecutive hyphens or underscores
  • 默认情况下同时处理下划线和连字符(可使用第二个参数配置)
  • 带有 unicode 字符的字符串
  • 以连字符或下划线结尾的字符串
  • 具有连续连字符或下划线的字符串

Here's a link to live tests: http://jsfiddle.net/avKzf/2/

这是现场测试的链接:http: //jsfiddle.net/avKzf/2/

Here are results from tests:

以下是测试结果:

  • input: "ab-cd-ef", result: "abCdEf"
  • input: "ab-cd-ef-", result: "abCdEf"
  • input: "ab-cd-ef--", result: "abCdEf"
  • input: "ab-cd--ef--", result: "abCdEf"
  • input: "--ab-cd--ef--", result: "AbCdEf"
  • input: "--ab-cd-__-ef--", result: "AbCdEf"
  • 输入:“ab-cd-ef”,结果:“abCdEf”
  • 输入:“ab-cd-ef-”,结果:“abCdEf”
  • 输入:“ab-cd-ef--”,结果:“abCdEf”
  • 输入:“ab-cd--ef--”,结果:“abCdEf”
  • 输入:“--ab-cd--ef--”,结果:“AbCdEf”
  • 输入:“--ab-cd-__-ef--”,结果:“AbCdEf”

Notice that strings that start with delimiters will result in a uppercase letter at the beginning. If that is not what you would expect, you can always use lcfirst. Here's my lcfirst if you need it:

请注意,以分隔符开头的字符串将导致以大写字母开头。如果这不是您所期望的,您可以随时使用 lcfirst。如果您需要,这是我的 lcfirst:

function lcfirst(str) {
    return str && str.charAt(0).toLowerCase() + str.substring(1);
}

回答by Nalan Madheswaran

Use inbuilt camelcase method in jquery:

在 jquery 中使用内置的驼峰法:

$.camelCase($("#text").html());

回答by xameeramir

You can also implement a pure javascript extension method like this:

你也可以像这样实现一个纯 javascript 扩展方法:

String.prototype.capitalize = function () {

    return this.toLowerCase().replace(/\b[a-z]/g, function (letter) {
        return letter.toUpperCase();
    });
};

And call it like this:

并这样称呼它:

"HELLO world".capitalize()

回答by surinder singh

    function camelCase(str){
        str     = $.camelCase(str.replace(/[_ ]/g, '-')).replace(/-/g, '');
        return  str;//.substring(0,1).toUpperCase()+str.substring(1);
    },