jquery - 自动大写单词
问题描述
如果它在数字或符号旁边,我将如何让这个脚本大写字母。这是我目前的代码。因此,如果它在“1”或“-”旁边,它将显示为“1A”“-A”而不是“1a”“-a”
$.fn.capitalise = function() {
$.each(this, function() {
var split = this.value.split(' ');
for (var i = 0, len = split.length; i < len; i++) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1).toLowerCase();
}
this.value = split.join(' ');
});
return this;
};
$('#id1').on('input', function() {
$(this).capitalise();
}).capitalise();
解决方案
您可以使用正则表达式匹配一个非字母字符后跟一个字母字符,然后在所有匹配项上将其转换为大写。在您键入时,以下代码段将在数字/符号或空格后大写。
$(function() {
$.fn.capitalise = function() {
//get existing value from input
let currentValue = $(this).val();
//apply regex replace to uppercase characters after number/symbol/whitespace
let newValue = currentValue.replace(/[^a-zA-Z]([a-zA-Z])/g, function(match) {
return match.toUpperCase();
});
//set new value to input
$(this).val(newValue);
};
$('#id1').on('input', function() {
$(this).capitalise();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="id1">Type here to auto-capitalize after number/symbol/whitespace:</label>
<br/>
<input id="id1"/>
如果不需要在空格后大写,只需添加\s
到正则表达式的第一部分:
/[^a-zA-Z\s]([a-zA-Z])/g
推荐阅读
- c - 在 C 语言中没有任何循环就可以打印数组吗?
- c++ - 获取输入时,halfdelay() 和 cbreak() + timeout() 有什么区别?
- node.js - 当我 POST 到 MongoDB 时,只保存 _id 并且
- javascript - React Native - 如何监听权限变化?
- scala - DatabaseException - 不能在 $in 下嵌套 $ (reactivemongo)
- mysql - 具有多个条件和空值的 SQL 查询
- javascript - 状态表单选项的 Javascript 条件
- python - AttributeError:“ConvertModel”对象没有“seek”属性
- postgresql - GCP - 通过 terraform 创建 postgreSQL - 使用 VPC
- json - 为什么我无法在 Xamarin.Forms 中解析我的 JSON?