2015-11-25 34 views
2

我這裏有一個的jsfiddle - https://jsfiddle.net/3e91ropp/jQuery的 - 在輸入字段中的字符計數不計空格

我簡單需要一種方法來計算在不計空格輸入字段中的字符數。

我需要驗證一個電話號碼字段有至少10個數字。

我可以使用length屬性,但算數,我不想做

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

回答

4

你可以使用.replace() method刪除空格位:

Updated Example

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

使用'\ s +',它比'\ s'好 – Tushar

+0

@Tushar以什麼方式更好?性能明智?更新。 –

+0

是的,在性能方面,嘗試在regex101上調試正則表達式'\ s'和'\ s +',並查看完成匹配所需的步驟數。 – Tushar

相關問題