JavaScript string array Conversion Function

Source: Internet
Author: User

Two custom js functions that implement mutual conversion between strings and arrays hope to be useful to you:

Copy to ClipboardReference: [www.bkjia.com] 1 function StringToArray (str, substr ){
2
3/* function: Splits a string into an Array Based on the specified string.
4 parameters:
5 str: string to be converted
6 substr: Split string
7 return value:
8. converted Array
9 */
10 var arrTmp = new Array ();
11
12 if (substr = ""){
13 arrTmp. push (str );
14 return arrTmp;
15}
16
17 var I = 0, j = 0, k = str. length;
18
19 while (I <k ){
20 j = str. indexOf (substr, I );
21
22 if (j! =-1 ){
23 if (str. substring (I, j )! = "") {ArrTmp. push (str. substring (I, j ));}
24 I = j + 1;
25} else {
26 if (str. substring (I, k )! = "") {ArrTmp. push (str. substring (I, k ));}
27 I = k;
28}
29}
30
31 return arrTmp;
32}
33
34
35 function ArrayToString (arr, str ){
36
37/* function: convert an array to a string based on the delimiter (string ).
38 parameters:
39 arr: String Array to be converted
40 str: Split string
41 return values:
42. converted string
43 */
44 var strTmp = "";
45
46 for (var I = 0; I <arr. length; I ++ ){
47 if (arr [I]! = ""){
48 if (strTmp = ""){
49 strTmp = arr [I];
50} else {
51 strTmp = strTmp + str + arr [I];
52}
53}
54}
55
56 return strTmp;
57}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.