问题描述:

I have bunch of string and would like to split and wrap them with html tag. I created a small example but my attempt has failed:

http://jsbin.com/taweparota/1/edit?html,js,output

var str = '0123456789';

str = str.split('');

var temp = '';

for ( var i = 0; i < str.length; i++ )

{

if(i === 0){

temp += '<div>'+str[i]+'</div>';

}else if(i % 3 == 0){

temp += '<div>'+str[i]+'</div>';

}else{

temp += str[i];

}

}

console.log(temp);

My expected output will be

012345 and so on. And the group by 2 can be change, like i can change the length of the content i want to 3 and the loop still work. I don't know why my above attempt failed, need help.

网友答案:

You can do it like this:

var result = '0123456789'.match(/.{1,2}/g)
                         .map(i => '<div>' + i + '</div>')
                         .join('');

console.log(result);
相关阅读:
Top