How to get the length of innerHTML (total characters) in JavaScript?

I'm trying to get the length of the characters that I get from innerHTML , and this seems like a last resort, but it can't seem to be a more efficient way, since the data is inside the slider, I'm trying to use to get a lower value and a higher value.

 var lvalue=document.getElementById("lval").innerHTML; 

then I spat out the line in spaces:

 var larr=lvalue.split(" "); 

The innerHTML value is similar to this "2413dsk 134dfa134".

And when I use larr[0].length , I get 1 when I need 7. Is there a solution?

+4
source share
4 answers

I think it will look something like this:

 var lvalue = document.getElementById("lval").innerHTML; var larr = lvalue.split(' '); var len = 0; // For each iterates over the index of arrays for(var i in larr) { len += larr[ i ].length // Acummulate the length of all the strings } 

Or, alternatively, you can first calculate the spaces and then subtract it from the total length.

 // Some people argue about extending the native objects // but in this case I think this method is a natural fit. String.prototype.count = function( character ) { var l = 0; // `this` refers to the string itself for(var c in this) n = this[ c ] === character ? ++n : n; return n; } 

Then use it like this:

 var lvalue = document.getElementById("lval").innerHTML; // Subtract total length minus the number of spaces var len = lvalue.length - lvalue.count(' '); 
+3
source

This may be caused by a prior or leading space.

Try trimming extra spaces:

 var lvalue=document.getElementById("lval").innerHTML.replace(/^\s+/gi,'').replace(/\s+$/gi,''); var larr=lvalue.split(" "); 
+1
source

I see no problems with your code. I run the test here: http://desdegdl.com/lval.html You probably have one or more spaces at the beginning of the internal HTML lval .

0
source

If there is someone like me who doesn't want to use jQuery, here is an example in javascript (only) ...

Files

Html file ...

 <!-- start body --> <body> <!-- start section --> <section id="bar"></section> <!-- end section --> </body> <!-- end body --> 

Javascript file ...

 /* start - wut element do ya wanna get? */ foo = document.getElementById('bar'); /* end - wut element do ya wanna get? */ /* start function */ function isEmpty(){ if (foo.innerHTML.length === 0) { /* your code here */ } } /* end function */ 

What I've done

In HTML

Pretty simple, I just created a section and assigned it an ID. This identifier will be used to call it in our javascript.

In javascript

In var fooI, I called the section for which I gave an identifier. After that, I created a function that “does something” if the length of the element is zero.

Questions

This works, but if you have a space or line break, the code will not consider it "empty" ...

0
source

Source: https://habr.com/ru/post/1394122/


All Articles