简体   繁体   English

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

[英]How to check string length with JavaScript

I want to get the string length when a key is pressed like StackOverflow does.我想像 StackOverflow 那样按下一个键时获取字符串长度。

StackOverflow 显示长度的示例

I have tried to do this with onblur , but it's not working.我曾尝试使用onblur执行此操作,但它不起作用。 How do I do this?我该怎么做呢?

As for the question which event you should use for this: use the input event, and fall back to keyup / keydown in 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.length answer is only reliable when you're certain that only BMP Unicode symbols will be entered.只有当您确定只会输入 BMP Unicode 符号时, string.length答案才是可靠的。 For example, 'a'.length == 1 , as you'd expect.例如,如您所料, 'a'.length == 1

However, for supplementary (non-BMP) symbols, things are a bit different.然而,对于补充(非 BMP)符号,情况有点不同。 For example, ''.length == 2 , even though there's only one Unicode symbol there.例如, ''.length == 2 ,即使那里只有一个 Unicode 符号。 This is because JavaScript exposes UCS-2 code units as “characters” .这是因为JavaScript 将 UCS-2 代码单元公开为“字符”

Luckily, it's still possible to count the number of Unicode symbols in a JavaScript string through some hackery.幸运的是,仍然可以通过一些技巧来计算 JavaScript 字符串中 Unicode 符号的数量。 You could use Punycode.js 's utility functions to convert between UCS-2 strings and Unicode code points for this:为此,您可以使用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`!)

PS I just noticed the counter script that Stack Overflow uses gets this wrong. PS 我刚刚注意到 Stack Overflow 使用的计数器脚本弄错了。 Try entering尝试输入, and you'll see that it (incorrectly) counts as two characters. ,您会看到它(错误地)算作两个字符。

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.它在 IE9 中仍然不是 100%,因此您将不得不等待 IE9 完全淘汰。 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.然而,根据我对这个问题的回答,输入不仅仅是我介绍的方法的合适替代品,所以我建议切换。

Use keyup event使用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.只是给那些建议 keydown 的人的注释。 That won't work.那行不通的。 The keydown fires before character is added to the input box or textarea, so the length of the value would be wrong (one step behind). keydown 在字符添加到输入框或文本区域之前触发,因此值的长度是错误的(落后一步)。 Therefore, the only solution that works is keyup, which fires after the character is added.因此,唯一可行的解决方案是 keyup,它会在添加字符触发。

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;
});

The quick and dirty way would be to simple bind to the keyup event.快速而肮脏的方法是简单地绑定到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捕获)

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

It will return the length of string它将返回字符串的长度

Instead of blur use keydown event.而不是blur使用keydown事件。

 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首先你需要定义一个按键处理程序或某种事件触发器来监听,顺便说一句,获取长度真的很简单,就像上面提到的

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:我不确定你在 blur 上尝试过它是什么意思,但是要获取任何字符串的长度,请使用 its.length 属性,因此在文本框或文本区域的情况下:

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

Changing that ID, of course, to whatever the actual ID is.当然,将该 ID 更改为实际 ID。

Basically: assign a keyup handler 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.基本上:为<textarea>元素分配一个keyup处理程序,在其中计算<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>

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

Leaving a reply (and an answer to the question title), For the future googlers...留下回复(以及问题标题的答案),对于未来的谷歌员工......

You can use .length to get the length of a string.您可以使用.length来获取字符串的长度。

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

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

/*"Mozilla is 7 code units long" */ /*“Mozilla 有 7 个代码单元”*/

console.log('The empty string has a length of ' + empty.length); console.log('空字符串的长度为' + empty.length);

/*"The empty string has a length of 0" */ /*"空字符串的长度为0" */

If you intend to get the length of a textarea say id="txtarea" then you can use the following code.如果您打算获取textarea的长度,比如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.您应该能够将其与 BMP Unicode 符号一起使用。 If you want to support "non BMP Symbols" like (), then its an edge case, and you need to find some work around.如果你想支持像 () 这样的“非 BMP 符号”,那么它是一个边缘案例,你需要找到一些解决方法。

That's the function I wrote to get string in Unicode characters:这是我编写的用于获取 Unicode 字符字符串的函数:

function nbUnicodeLength(string){
    var stringIndex = 0;
    var unicodeIndex = 0;
    var length = string.length;
    var second;
    var first;
    while (stringIndex < length) {

        first = string.charCodeAt(stringIndex);  // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
        if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) {
            second = string.charCodeAt(stringIndex + 1);
            if (second >= 0xDC00 && second <= 0xDFFF) {
                stringIndex += 2;
            } else {
                stringIndex += 1;
            }
        } else {
            stringIndex += 1;
        }

        unicodeIndex += 1;
    }
    return unicodeIndex;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM