将字符串拆分为数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将字符串拆分为数组相关的知识,希望对你有一定的参考价值。

I needed to break down a long string today and insert line breaks so I wrote this little function. You can use it to split a long string into chunks of a defined length and get them as an array or join them by a defined character (e.g. <br />). Have fun.
  1. /**
  2.  * Splits string into chunks of defined lengths
  3.  * Returns an array by default or the joined version of the array if join_with is supplied
  4.  * @param string String to split
  5.  * @param number Size of the chunks to split the string into
  6.  * @param string Resulting array is joined into a string by this
  7.  * @return mixed Array with chunks or joined string
  8.  */
  9. function str_split(str, chunk_size, join_with)
  10. {
  11. var a_chunks = [], index = 0;
  12. do
  13. {
  14. a_chunks.push(str.slice(index, index+chunk_size));
  15. index += chunk_size;
  16. }
  17. while (index < str.length)
  18. return join_with ? a_chunks.join(join_with) : a_chunks;
  19. }
  20.  
  21.  
  22. // examples
  23. var str = 'thisisaverylongstringthatjustwontstopitgoesonandonandonandon';
  24. // split string into array
  25. var a = str_split(str, 5);
  26. // split string to fit a specified length in page
  27. document.write(str_split(str, 20, '<br />'));
  28. document.write('<br />');
  29. // split string (like a product identifier) to contain a new char
  30. document.write(str_split('203482034823329', 5, '-'));

以上是关于将字符串拆分为数组的主要内容,如果未能解决你的问题,请参考以下文章

如何将包含表情符号的字符串拆分为数组?

按句点将字符串拆分为字符串 [] 但返回一个空数组

C#:如何将多个字符串拆分为二维数组?

将数组拆分为列 pyspark-array 长度变量

为啥将拆分为 wav 文件的旋律转换为拆分的 mp3 会在片段边界处产生不好的声音?

如何在 C++ 中将字符串拆分为数组