如何使用jQuery计算文本框中字符的数量?
$("#id").val().length < 3
只计算了三个字符空间,而不是字符的数量。
如何使用jQuery计算文本框中字符的数量?
$("#id").val().length < 3
只计算了三个字符空间,而不是字符的数量。
计算包括空格在内的字符长度:
$("#id").val().length
计算不包括空格的字符长度:
$("#id").val().replace(/ /g,'').length
仅删除开头和结尾的空格:
$.trim($("#test").val()).length
" t e s t "
将被解析为://" t e s t "
$("#id").val();
//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7
这里是使用它们全部的演示。
.length
来计算字符数量,使用$.trim()
函数去除空格,使用replace(/ /g,'')
将多个空格替换为一个空格。以下是一个例子: var str = " Hel lo ";
console.log(str.length);
console.log($.trim(str).length);
console.log(str.replace(/ /g,'').length);
输出:
20
7
5
由于这个问题的所有给出的答案都对我无效(我在想jQuery是否在这方面有所改变?),因此我添加了在我的情况下有效的解决方案,即使用$('#myelement').text().length;
来确定标签内字符的数量(由标签名称或ID定义)。
var x = $('h1').text().length;
console.log(x);
$('#solution').text(x);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>How many characters are in this H1?</h1>
<p>This is just some more text.</p>
<p style="font-size: 1.4em;">Solution: There are <span id="solution"></span> characters in the h1 tag, including spaces</p>
$("#id").val().length
返回字符串中的字符数。有什么问题吗? - gen_Eric$("#id").val().length
,但当我使用.html()
打印它时,它仍然是0。 - yaakov