我怎样才能让变量的首字母总是大写? [英] How can I make the first letter of a variable always capital?

查看:142
本文介绍了我怎样才能让变量的首字母总是大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在JavaScript中将字符串的第一个字母大写


我正在做一些叫做HTML测验的东西。它是用JavaScript制作的。当用户首次输入时,他们必须输入他们的名字。一旦他们点击提交,他们输入的名称将被保存到一个变量中。当它说:


亲爱的纳当,

您即将参加HTML测验。请..... .....

我认为它看起来更像这样:



< blockquote>

亲爱的Nathan,



您即将参加HTML测验。请..... .....

但是,如果用户以小写字母开头输入名称,它将保持这种状态。无论如何,如果第一个字母是小写使用jQuery ,它会变成大写字母吗?例如,这里是一个简单的名字输入脚本: http ://jsfiddle.net/RcLt6/



如果您输入的名字全部小写,当然,它将全部为小写。无论如何,我怎样才能让输入的第一个字符总是被大写?

解决方案



  str = str [0] .toUpperCase()+ str.slice(1); 

现场演示: http://jsfiddle.net/qNJVQ/




顺便说一下,将INPUT放在LABEL中 - 这样,您不必为属性使用来将标签与输入字段相关联:

 < label> 
名称:< input type =text>
< / label>


Possible Duplicate:
Capitalize the first letter of string in JavaScript

I am making something called "The HTML Quiz". It's made with JavaScript. When the user first enters it, they have to enter their name. Once they click submit, the name they enter is saved into a variable. It doesn't look nice when it says:

Dear nathan,

You are about to take The HTML Quiz. Please.....

I think it looks better like this:

Dear Nathan,

You are about to take The HTML Quiz. Please.....

But if the user enters their name starting with a lowercase letter, it will stay that way. Is there anyway to make that first letter turn into an uppercase letter if it is lowercase with jQuery?

For example, here is a simple name enter script: http://jsfiddle.net/RcLt6/

If you enter your name in all lowercase, of course, it will be all lowercase. How can I make the first character entered always be capitalized no matter what?

解决方案

This will do it:

str = str[0].toUpperCase() + str.slice(1);

Live demo: http://jsfiddle.net/qNJVQ/


Btw, put the INPUT inside the LABEL - that way you won't have to use the for attribute to associate the label with the input field:

<label>
    Name: <input type="text">
</label>

这篇关于我怎样才能让变量的首字母总是大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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