【问题标题】:Auto Capitalise Words自动大写单词
【发布时间】:2020-04-26 01:10:50
【问题描述】:

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

【问题讨论】:

    标签: jquery capitalize


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢你,安德鲁。有个小问题,输入的第一个字母不大写,只在第一个单词或空格后大写。
    • 另外,它不应该允许整个单词全部大写,只允许第一个字母。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 2019-06-15
    • 1970-01-01
    相关资源
    最近更新 更多