I have given string "asdlfjsahdkljahskl" and have given array [1,2,3,1,7,2,1,2].My final output should be a, sd, lfj, s, ahdklja, hs, kl.
I know how to split the string but I don't know how to compare the string and cut according to given array
HTML Code
<button onclick="myFunction()">click me</button>
<p id="demo"></p>
JavaScript
var width = [1,4,2,6,1,1,10,1];
function myFunction() {
var str = "abcdefghijklmnopqrstuvwxyz";
var res = str.split("");
for(var j=0; j.length;j++){
document.write(width[j]);
}
document.getElementById("demo").innerHTML = res;
}
Thank you for your help
Chandan Rai
10.5k2 gold badges22 silver badges29 bronze badges
3 Answers 3
You could slice the string with a stored value and a new length.
var string = "asdlfjsahdkljahskl",
array = [1, 2, 3, 1, 7, 2, 1, 2],
p = 0,
result = array.map(function (a) {
return string.slice(p, p += a);
});
console.log(result);
The same with a for loop
var string = "asdlfjsahdkljahskl",
array = [1, 2, 3, 1, 7, 2, 1, 2],
p = 0,
i = 0,
result = []
for (i = 0; i < array.length; i++) {
result.push(string.slice(p, p + array[i]));
p += array[i];
}
console.log(result);
answered Jan 23, 2017 at 16:58
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
danny
how would this be possible without .map
mhodges
@danny you can use any iterator, honestly (assuming you use them properly) - my answer uses
.forEach() if you are interested in that onedanny
I am beginner, so I am looking very simple logic not using for each or .map. Thanks for helping
var string="asdlfjsahdkljahsxkl",
array=[1,2,3,1,7,2,1,2];
function myFunction() {
array.forEach(function(index){
var yourvalue=string.slice(0,index);
console.log(yourvalue);
document.getElementById("demo").innerHTML += yourvalue+'\n';
string=string.slice(index,string.length);
});
}
<button onclick="myFunction()">click me</button>
<p id="demo"></p>
answered Jan 23, 2017 at 16:56
LellisMoon
5,0282 gold badges14 silver badges25 bronze badges
Comments
An alternative to Nina's answer is to convert your string to an array, like you have done, and use the .splice() function like so:
var str = "asdlfjsahdkljahskl",
arr = [1, 2, 3, 1, 7, 2, 1, 2];
function extractValues (str, strLens) {
str = str.split("");
strLens.forEach(function (strLen) {
console.log(str.splice(0, strLen).join(""));
});
}
extractValues(str, arr);
answered Jan 23, 2017 at 17:18
mhodges
11.2k2 gold badges32 silver badges48 bronze badges
2 Comments
danny
what does .foreach do ? does it compare every array element. I am running on my local editor is giving me error
lang-js
j.lengthdoes not make any sense since it is a number.