首页 > 解决方案 > 自动大写单词

问题描述

如果它在数字或符号旁边,我将如何让这个脚本大写字母。这是我目前的代码。因此,如果它在“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();

标签: jquerycapitalize

解决方案


您可以使用正则表达式匹配一个非字母字符后跟一个字母字符,然后在所有匹配项上将其转换为大写。在您键入时,以下代码段将在数字/符号或空格后大写。

$(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

推荐阅读