最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - count number of characters in a input field excluding spaces - Stack Overflow

programmeradmin4浏览0评论

I have a jsfiddle here - /

I simple need a way to count the number of characters in an input field excluding spaces.

I need to validate a phone number field to have at least 10 numbers.

I can use the length property but that counts spaces which I don't want to do

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

I have a jsfiddle here - https://jsfiddle/3e91ropp/

I simple need a way to count the number of characters in an input field excluding spaces.

I need to validate a phone number field to have at least 10 numbers.

I can use the length property but that counts spaces which I don't want to do

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

Share Improve this question edited Nov 26, 2015 at 0:27 Josh Crozier 241k56 gold badges400 silver badges313 bronze badges asked Nov 25, 2015 at 15:31 ttmtttmt 5,00631 gold badges114 silver badges167 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

You could remove the spaces using the .replace() method:

Updated Example

$('.field').val().replace(/\s+/g, '').length
发布评论

评论列表(0)

  1. 暂无评论