简体   繁体   English

JavaScript变量少于4个字符

[英]JavaScript variable less than 4 characters

I have "name" JavaScript variable. 我有“名字”JavaScript变量。 If variable "name" contains less than 4 characters I want to execute line: msg('name','Your name must contain minimum 4 characters.')'; 如果变量“name”包含少于4个字符,我想执行line: msg('name','Your name must contain minimum 4 characters.')'; I have tried something like this but it interpretated mathematical. 我尝试过这样的东西,但它解释了数学。 Any idea? 任何想法? Thank you. 谢谢。

if(name < 4 ) {
  msg('name','Your name must contain minimum 4 characters.');
  return false;
}
if (name.length < 4) {
   ...
}

You probably want to check the length of the string, not the numeric value of the string itself: 您可能想要检查字符串的length ,而不是字符串本身的数值:

if(name.length < 4) {
    // ...
if(name.length < 4) {
    //Do something
}

You have to check the length of the variable. 你必须检查变量的length

有趣的事实:

  • length can also be used to check the length of an Array length也可用于检查Array的长度
  • \\n (new line) is also counted as a character. \\n (新行)也算作一个字符。

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. 幸运的是,仍然可以通过一些hackery来计算JavaScript字符串中Unicode符号的数量。 You could use Punycode.js 's utility functions to convert between UCS-2 strings and UTF-16 code points for this: 您可以使用Punycode.js的实用程序函数在UCS-2字符串和UTF-16代码点之间进行转换:

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

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

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