我正在尝试从innerHTML获得我获得的角色的长度,并且它有点归根结底,但似乎找不到更有效的方式,因为数据在我正在尝试的滑块内用来获得更低的价值和更高的价值.
var lvalue=document.getElementById("lval").innerHTML;
然后我在空间中吐出字符串:
var larr=lvalue.split(" ");
innerHTML值类似于“2413dsk 134dfa134”.
当我使用larr [0] .length时,我需要7时得到1.是否有解决方案?
解决方法:
我认为它会是这样的:
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
}
或者,您可以先计算空间,然后从总长度中减去它.
// 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;
}
然后像这样使用它:
var lvalue = document.getElementById("lval").innerHTML;
// Subtract total length minus the number of spaces
var len = lvalue.length - lvalue.count(' ');
标签:javascript,character,innerhtml,html
来源: https://codeday.me/bug/20190621/1251293.html