Reputation: 187
I need to separate the first three numberss and then the fourth to “separate them”. Finally, the code should look like:
the first three numbers: 1,1,1fourth number: 2
the first three numbers: 3,3,3fourth number: 4
var numb = document.getElementById("text").innerHTML;
var numb, text, fLen, i;
fLen = numb.length;
text = for (i = 0; i < fLen; i++) {
text += "the first three numbers:" + numb[i] + "fourth number:"+ numb[i] +"<br>";
}
document.getElementById("text").innerHTML = text;
<div id="text">1, 1, 1, 2, 3, 3, 3, 4</div>
Upvotes: 1
Views: 262
Reputation: 39
I would use lodash for this.
Edited to be done without lodash.
<html>
<div id="text">1, 1, 1, 2, 3, 3, 3, 4</div>
</html>
<script>
var numb = document.getElementById("text").innerHTML.split(/,\s*/);
console.log(numb)
var chunk_array = []
var i,j,temparray,chunk = 4;
for (i=0,j=numb.length; i<j; i+=chunk) {
temparray = numb.slice(i,i+chunk);
chunk_array.push(temparray)
}
console.log(chunk_array)
result =''
chunk_array.forEach(element => result += "the first three numbers:" + element.slice(0,2).join(', ') + " fourth element: " + element[3] + "<br/>")
console.log(result)
document.getElementById("text").innerHTML = result;
</script>
Upvotes: 1
Reputation: 386883
You could take different names as the id
of html elements, because browsers take this name as variable for htis element. This is not relyable to use.
Take the string and split it by comma and possible following white space and iterate as long as the index is smaller than the length of the array.
Inside take three items from the array as first part and another as the fourth part.
var html = document.getElementById("text").innerHTML,
values = html.split(/,\s*/),
result = '',
i = 0;
while (i < values.length) {
result += "the first three numbers:" + values.slice(i, i += 3).join(', ');
result += " fourth number: "+ values[i++] + "<br>";
}
document.getElementById("text").innerHTML = result;
<div id="text">1, 1, 1, 2, 3, 3, 3, 4</div>
Upvotes: 1