How do you get the length of a string?

后端 未结 10 1525
星月不相逢
星月不相逢 2020-12-12 12:43

How do you get the length of a string in jQuery?

相关标签:
10条回答
  • 2020-12-12 12:57

    jQuery is a JavaScript library.

    You don't need to use jQuery to get the length of a string because it is a basic JavaScript string object property.

    somestring.length;
    
    0 讨论(0)
  • 2020-12-12 13:06

    The easiest way:

    $('#selector').val().length
    
    0 讨论(0)
  • 2020-12-12 13:07

    same way you do it in javascript:

    "something".length

    0 讨论(0)
  • 2020-12-12 13:08

    In some cases String.length might return a value which is different from the actual number of characters visible on the screen (e.g. some emojis are encoded by 2 UTF-16 units):

    MDN says: This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.

    0 讨论(0)
  • 2020-12-12 13:14

    You don't need jquery, just use yourstring.length. See reference here and also here.

    Update:

    To support unicode strings, length need to be computed as following:

    [..."                                                                    
    0 讨论(0)
  • 2020-12-12 13:14

    A somewhat important distinction is if the element is an input or not. If an input you can use:

    $('#selector').val().length;
    

    otherwise if the element is a different html element like a paragraph or list item div etc, you must use

    $('#selector').text().length;
    
    0 讨论(0)
提交回复
热议问题