Como você obtém o comprimento de uma corda?
-
20-08-2019 - |
Pergunta
Como você obtém o comprimento de uma corda no jQuery?
Outras dicas
A maneira mais fácil:
$('#selector').val().length
JQuery é uma biblioteca JavaScript.
Você não precisa usar o jQuery para obter o comprimento de uma string, porque é uma propriedade básica do objeto de string javascript.
somestring.length;
Html
<div class="selector">Text mates</div>
ROTEIRO
alert(jQuery('.selector').text().length);
RESULTADO
10
Você não precisa usar o jQuery.
var myString = 'abc';
var n = myString.length;
n será 3.
Uma distinção um tanto importante é se o elemento é uma entrada ou não. Se uma entrada você pode usar:
$('#selector').val().length;
Caso contrário, se o elemento for um elemento HTML diferente, como um parágrafo ou item de lista div, etc., você deve usar
$('#selector').text().length;
Não é jQuery você precisa, é JS:
alert(str.length);
da mesma forma que você faz isso em JavaScript:
"something".length
Em jQuery:
var len = jQuery('.selector').val().length; //or
( var len = $('.selector').val().length;) //- If Element is Text Box
OU
var len = jQuery('.selector').html().length; //or
( var len = $('.selector').html().length; ) //- If Element is not Input Text Box
Em JS:
var len = str.len;
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.