Javascript按给定的数组元素拆分字符串

时间:2017-01-23 16:52:29

标签: javascript arrays

我已经给出了字符串"asdlfjsahdkljahskl",并给出了数组[1,2,3,1,7,2,1,2]。我的最终输出应为asdlfjsahdkljahskl

我知道如何分割字符串,但我不知道如何根据给定数组比较字符串和剪切

HTML代码

<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;
 }

感谢您的帮助

3 个答案:

答案 0 :(得分:5)

您可以使用存储的值和新长度对字符串进行切片。

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);

for循环相同

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);

答案 1 :(得分:0)

&#13;
&#13;
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);
});
  }
&#13;
<button onclick="myFunction()">click me</button>
<p id="demo"></p>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

Nina答案的替代方法是将您的字符串转换为数组,就像您所做的那样,并使用.splice()函数,如下所示:

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);