【问题标题】:jQuery - count number of characters in a input field excluding spacesjQuery - 计算输入字段中的字符数,不包括空格
【发布时间】:2015-11-25 15:31:56
【问题描述】:

我在这里有一个 jsfiddle - https://jsfiddle.net/3e91ropp/

我只是需要一种方法来计算输入字段中不包括空格的字符数。

我需要验证一个电话号码字段至少有 10 个号码。

我可以使用长度属性,但这会计算我不想做的空格

$(function() {
  $('button').on('click', function() {
    console.log($('.field').val().length);
  })
});
.wrap {
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <input class="field" type="text" />
  <button>Click</button>
</div>

【问题讨论】:

    标签: javascript jquery input


    【解决方案1】:

    您可以使用.replace() method 删除空格:

    Updated Example

    $('.field').val().replace(/\s+/g, '').length
    

    【讨论】:

    • 使用\s+,比\s
    • 是的,性能方面,尝试在 regex101 上调试正则表达式 \s\s+ 并查看完成匹配所需的步骤数。
    猜你喜欢
    • 2015-02-06
    • 2014-05-13
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    相关资源
    最近更新 更多