简体   繁体   中英

Split and wrap string with html tag base on character length

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

If you want to change your grouping to 3:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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