简体   繁体   English

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

[英]Javascript splitting string by given array element

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 . 我给了字符串"asdlfjsahdkljahskl"并给了数组[1,2,3,1,7,2,1,2]我的最终输出应该是asdlfjsahdkljahskl

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 HTML代码

<button onclick="myFunction()">click me</button>
<p id="demo"></p>

JavaScript 的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 谢谢您的帮助

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

 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> 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM