如何使用 JavaScript 检查字符串长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11046797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:13:37  来源:igfitidea点击:

How to check string length with JavaScript

javascriptforms

提问by NullPoiиteя

I want to get the string length when a key is pressed like StackOverflow does.

我想在像 StackOverflow 那样按下某个键时获取字符串长度。

Example of StackOverflow showing length

显示长度的 StackOverflow 示例

I have tried to do this with onblur, but it's not working. How do I do this?

我试图用 来做到这一点onblur,但它不起作用。我该怎么做呢?

回答by Mathias Bynens

As for the question which event you should use for this: use the inputevent, and fall back to keyup/keydownin older browsers.

至于您应该为此使用哪个事件的问题:使用该input事件,并回退到keyup/keydown在旧浏览器中。

Here's an example, DOM0-style:

这是一个 DOM0 样式的示例:

someElement.oninput = function() {
  this.onkeydown = null;
  // Your code goes here
};
someElement.onkeydown = function() {
  // Your code goes here
};


The other question is how to count the number of characters in the string. Depending on your definition of “character”, all answers posted so far are incorrect. The string.lengthanswer is onlyreliable when you're certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1, as you'd expect.

另一个问题是如何计算字符串中的字符数。根据您对“性格”的定义,到目前为止发布的所有答案都是不正确的。只有当您确定只会输入 BMP Unicode 符号时,string.length答案可靠。例如,'a'.length == 1正如您所期望的那样。

However, for supplementary (non-BMP) symbols, things are a bit different. For example, ''.length == 2, even though there's only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.

但是,对于补充(非 BMP)符号,情况有点不同。例如,''.length == 2即使那里只有一个 Unicode 符号。这是因为JavaScript 将 UCS-2 代码单元公开为“字符”

Luckily, it's still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js's utility functions to convert between UCS-2 strings and Unicode code points for this:

幸运的是,仍然可以通过一些技巧来计算 JavaScript 字符串中 Unicode 符号的数量。为此,您可以使用Punycode.js的实用程序函数在 UCS-2 字符串和 Unicode 代码点之间进行转换:

// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('').length; // 1 (note that `''.length == 2`!)

P.S. I just noticed the counter script that Stack Overflow uses gets this wrong. Try entering , and you'll see that it (incorrectly) counts as two characters.

PS 我刚刚注意到 Stack Overflow 使用的计数器脚本出错了。尝试输入,您会看到它(错误地)算作两个字符。

回答by NullPoiиteя

UPDATE:Since I wrote this, the input event has gotten a decent level of support. It is still not 100% in IE9, so you will have to wait a bit until IE9 is fully phased out. In light of my answer to this question, however, input is more than a decent replacement for the method I've presented, so I recommend switching.

更新:自从我写这篇文章以来,输入事件得到了相当程度的支持。它在 IE9 中仍然不是 100%,因此您将不得不等待一段时间,直到 IE9 完全淘汰。然而,根据我对这个问题的回答,输入不仅仅是我提出的方法的一个不错的替代品,所以我建议切换。

Use keyupevent

使用keyup事件

var inp = document.getElementById('myinput');
var chars = document.getElementById('chars');
inp.onkeyup = function() {
  chars.innerHTML = inp.value.length;
}
<input id="myinput"><span id="chars">0</span>

EDIT:

编辑:

Just a note for those that suggest keydown. That won't work. The keydown fires beforecharacter is added to the input box or textarea, so the length of the value would be wrong (one step behind). Therefore, the only solution that works is keyup, which fires afterthe character is added.

只是对那些建议使用 keydown 的人的说明。那行不通。keydown字符添加到输入框或 textarea之前触发,因此值的长度将是错误的(落后一步)。因此,唯一有效的解决方案是 keyup,它添加字符触发。

回答by Trinh Hoang Nhu

You should bind a function to keyup event

您应该将函数绑定到 keyup 事件

textarea.keyup = function(){
   textarea.value.length....
} 

with jquery

使用 jquery

$('textarea').keyup(function(){
   var length = $(this).val().length;
});

回答by Me.Name

The quick and dirty way would be to simple bind to the keyupevent.

快速而肮脏的方法是简单地绑定到keyup事件。

$('#mytxt').keyup(function(){
    $('#divlen').text('you typed ' + this.value.length + ' characters');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type=text id=mytxt >
<div id=divlen></div>

But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup)

但更好的是将可重用函数绑定到多个事件。例如,对于 change(),您还可以预期文本更改,例如粘贴(使用上下文菜单,快捷方式也会被 捕获keyup

回答by Lakshitha Udara

 var myString = 'sample String';   var length = myString.length ;

first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above

首先,您需要定义一个按键处理程序或某种事件触发器来侦听,顺便说一句,获取长度非常简单,如上所述

回答by Lakshitha Udara

function cool(d)
{
    alert(d.value.length);
}
<input type="text" value="" onblur="cool(this)">

It will return the length of string

它将返回字符串的长度

Instead of bluruse keydownevent.

而不是blur使用keydown事件。

回答by D. Strout

I'm not sure what you mean by having tried it onblur, but to get the length of any string, use its .length property, so in the case of a textbox or textarea:

我不确定你在 onblur 上试过是什么意思,但是要获得任何字符串的长度,请使用它的 .length 属性,所以在文本框或文本区域的情况下:

document.getElementById("textarea").value.length

Changing that ID, of course, to whatever the actual ID is.

当然,将该 ID 更改为任何实际 ID。

回答by KooiInc

Basically: assign a keyuphandler to the <textarea>element, in it count the length of the <textarea>and write the count to a separate <div>if its length is shorter than a minimum value.

基本上:keyup<textarea>元素分配一个处理程序,在其中计算元素的长度,如果其长度小于最小值,则将计数<textarea>写入单独的元素<div>

Here's is an example-

这是一个例子——

var min = 15;
document.querySelector('#tst').onkeyup = function(e){
 document.querySelector('#counter').innerHTML = 
               this.value.length < min 
               ? (min - this.value.length)+' to go...'
               : '';
}
    
body {font: normal 0.8em verdana, arial;}
#counter {color: grey}
<textarea id="tst" cols="60" rows="10"></textarea>
<div id="counter"></div>

回答by Jeff Binnig

<html>
<head></head>
<title></title>
<script src="/js/jquery-3.2.1.min.js" type="text/javascript"></script>
<body>
Type here:<input type="text" id="inputbox" value="type here"/>
<br>
Length:<input type="text" id="length"/>
<script type='text/javascript'>
    $(window).keydown(function (e) {
    //use e.which
    var length = 0;
    if($('#inputbox').val().toString().trim().length > 0)
    {
        length = $('#inputbox').val().toString().trim().length;
    }

    $('#length').val(length.toString());
  })
</script>
</body>
</html>

回答by Mohd Abdul Mujib

Leaving a reply (and an answerto the question title), For the future googlers...

留下回复(以及问题标题的答案),对于未来的谷歌员工......

You can use .lengthto get the length of a string.

您可以使用.length来获取字符串的长度。

var x = 'Mozilla'; var empty = '';

console.log('Mozilla is ' + x.length + ' code units long');

/*"Mozilla is 7 code units long" */

console.log('The empty string has a length of ' + empty.length);

/*"The empty string has a length of 0" */

var x = 'Mozilla'; var 空 = '';

console.log('Mozilla 是 ' + x.length + ' 代码单位长');

/*“Mozilla 有 7 个代码单元长”*/

console.log('空字符串的长度为' + empty.length);

/*"空字符串的长度为0" */

If you intend to get the length of a textareasayid="txtarea"then you can use the following code.

如果你想得到一个textareasay的长度,id="txtarea"那么你可以使用下面的代码。

txtarea = document.getElementById('txtarea');
console.log(txtarea.value.length);

You should be able to get away with using this with BMP Unicode symbols. If you want to support "non BMP Symbols" like (), then its an edge case, and you need to find some work around.

您应该能够将它与 BMP Unicode 符号一起使用。如果你想支持像 () 这样的“非 BMP 符号”,那么它是一个边缘情况,你需要找到一些解决方法。