Javascript 变量首字母大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5122402/
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:45:16  来源:igfitidea点击:

Uppercase first letter of variable

javascriptjquery

提问by ryryan

I have searched over the web can can't find anything to help me. I want to make the first letter of each word upper case within a variable.

我在网上搜索过找不到任何可以帮助我的东西。我想在变量中将每个单词的第一个字母大写。

So far i have tried:

到目前为止,我已经尝试过:

toUpperCase();

And had no luck, as it uppercases all letters.

没有运气,因为它大写所有字母。

回答by Peter Olson

Use the .replace[MDN]function to replace the lowercase letters that begin a word with the capital letter.

使用.replace[MDN]函数将单词开头的小写字母替换为大写字母。

var str = "hello world";
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
alert(str); //Displays "Hello World"



Edit: If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.

编辑:如果您处理的不仅仅是 az 的单词字符,那么以下(更复杂的)正则表达式可能更适合您的目的。

var str = "петр данилович bj?rn über ?aque αλφα";
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
    return letter.toUpperCase();
});
alert(str); //Displays "Петр Данилович Bj?rn über ?aque Αλφα"

回答by vbullinger

Much easier way:

更简单的方法:

$('#test').css('textTransform', 'capitalize');

$('#test').css('textTransform', 'capitalize');

I have to give @Dementic some credit for leading me down the right path. Far simpler than whatever you guys are proposing.

我必须感谢@Dementic 带领我走上正确的道路。比你们提出的任何建议都简单得多。

回答by Jonathan Fingland

http://phpjs.org/functions/ucwords:569has a good example

http://phpjs.org/functions/ucwords:569有一个很好的例子

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function () {
        return .toUpperCase();
    });
}

(omitted function comment from source for brevity. please see linked source for details)

(为简洁起见,从源中省略了函数注释。有关详细信息,请参阅链接源)

EDIT: Please note that this function uppercases the first letter of each word (as your question asks) and not just the first letter of a string (as your question title asks)

编辑:请注意,此函数将每个单词的第一个字母(如您的问题所要求)大写,而不仅仅是字符串的第一个字母(如您的问题标题所要求)

回答by Dementic

just wanted to add a pure javascript solution ( no JQuery )

只是想添加一个纯 javascript 解决方案(没有 JQuery)

function capitalize(str) {
  strVal = '';
  str = str.split(' ');
  for (var chr = 0; chr < str.length; chr++) {
    strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
  }
  return strVal
}

console.log(capitalize('hello world'));

回答by Nicholas Hughes

I imagine you could use substring() and toUpperCase() to pull out the first character, uppercase it, and then replace the first character of your string with the result.

我想您可以使用 substring() 和 toUpperCase() 来提取第一个字符,将其大写,然后用结果替换字符串的第一个字符。

myString = "cheeseburger";
firstChar = myString.substring( 0, 1 ); // == "c"
firstChar.toUpperCase();
tail = myString.substring( 1 ); // == "heeseburger"
myString = firstChar + tail; // myString == "Cheeseburger"

I think that should work for you. Another thing to consider is that if this data is being displayed, you can add a class to its container that has the CSS property "text-transform: capitalize".

我认为这应该对你有用。另一件要考虑的事情是,如果正在显示此数据,您可以向其容器添加一个类,该类具有 CSS 属性“text-transform: capitalize”。

回答by Bruce Smith

To do this, you don't really even need Javascript if you're going to use

要做到这一点,如果你打算使用,你甚至不需要 Javascript

$('#test').css('textTransform', 'capitalize');

Why not do this as css like

为什么不这样做像 css 一样

#test,h1,h2,h3 { text-transform: capitalize; }

or do it as a class and apply that class to wherever you need it

或者将其作为一个类进行并将该类应用到您需要的任何地方

.ucwords { text-transform: capitalize; }

回答by Cypher

Ever heard of substr()?

听说过substr()吗?

For a starter :

首先:

$("#test").text($("#test").text().substr(0,1).toUpperCase()+$("#test").text().substr(1,$("#test").text().length));


[Update:]


[更新:]

Thanks to @FelixKlingfor the tip:

感谢@FelixKling的提示:

$("#test").text(function(i, text) {
    return text.substr(0,1).toUpperCase() + text.substr(1);
});

回答by mmalone

Building on @peter-olson's answer, I took a more object oriented approach without jQuery:

基于@peter-olson 的回答,我采用了一种更面向对象的方法,而不使用 jQuery:

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

alert("hello world".ucwords()); //Displays "Hello World"

Example: http://jsfiddle.net/LzaYH/1/

示例:http: //jsfiddle.net/LzaYH/1/

回答by Nick Chan Abdullah

var mystring = "hello World"
mystring = mystring.substring(0,1).toUpperCase() + 
mystring.substring(1,mystring.length)

console.log(mystring) //gives you Hello World

回答by IamMHussain

You can try this simple code with the features of ucwords in PHP.

您可以使用 PHP 中 ucwords 的功能来尝试这个简单的代码。

function ucWords(text) {
    return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');

It will keep the Upper Cases unchanged.

它将保持大写不变。