Javascript jQuery 去除前导和尾随空格
我想修剪该值(去掉前导和尾随空格)并使每个单词的第一个字母大写。当用户离开元素(模糊事件)时,
HTML 输入如下
<input id="iptFirstName" name="iptFirstName" type="text"/>
JS 代码段
$(document).ready(function(){
var iptFirstName = $("#iptFirstName");
iptFirstName.blur(validateForename);
});
function validateForename(){
var firstName= $("#iptFirstName").val;
//strip leading and trailing spaces
firstName= $.trim(firstName)
//change first letter in every word to uppercase
firstName= Capital(firstName);
//update input field whit new value
$("#iptFirstName").val(firstName);
}
function Capital(eleValue) {
var eleValue;
if (eleValue != "") {
var firstLetter = eleValue.substring(0, 1).touppercase();
var restOfWord = eleValue.substring(1, eleValue.length).tolowercase();
eleValue = firstLetter + restOfWord;
return eleValue;
}
}
请理解为什么它不起作用,或者也许有更好的方法来解决这个问题。
I want to trim the value (strip leading and trailing spaces) and make first letter in every word capital. When user leave from the element (blur event)
HTML input as follows
<input id="iptFirstName" name="iptFirstName" type="text"/>
JS piece of code
$(document).ready(function(){
var iptFirstName = $("#iptFirstName");
iptFirstName.blur(validateForename);
});
function validateForename(){
var firstName= $("#iptFirstName").val;
//strip leading and trailing spaces
firstName= $.trim(firstName)
//change first letter in every word to uppercase
firstName= Capital(firstName);
//update input field whit new value
$("#iptFirstName").val(firstName);
}
function Capital(eleValue) {
var eleValue;
if (eleValue != "") {
var firstLetter = eleValue.substring(0, 1).touppercase();
var restOfWord = eleValue.substring(1, eleValue.length).tolowercase();
eleValue = firstLetter + restOfWord;
return eleValue;
}
}
Please understand why it isn't working or maybe have a better approach to solve this problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个一定可行,只做了一些改变,
对
你
尝试一下
try this must work, only few changes done,
to
to
yo
你可以试试这个
$.trim(firstName).replace(/^([az])|\s+([az])/g, function ($1) {return $1.toUpperCase();})
You can try this
$.trim(firstName).replace(/^([a-z])|\s+([a-z])/g, function ($1) {return $1.toUpperCase();})
这样就可以了 -
演示 - http://jsfiddle.net/ipr101/QvATH/1
This would do it -
Demo - http://jsfiddle.net/ipr101/QvATH/1
您在代码中遇到了几个错误
http://jsfiddle.net/b3XhL/
You had several errors trought the code
http://jsfiddle.net/b3XhL/