In js, the most common code for converting arrays and strings is to use the join and split functions for operations. This is somewhat similar to array and character conversion in php and asp, next I will introduce the operation methods in js.
Method description:
1. join () method: used to put all elements in the array into a string. elements are separated by the specified separator.
Specify the separator method join ("$"); where $ can be any character
2. split () method: used to split a string into a string array.
StringObject. split (a, B) This is its syntax
A is a required field. It is used as the separator to separate the entire string. B is optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings are returned than the array specified by this parameter. If this parameter is not set, the entire string is split, regardless of its length.
I. Convert string to array
(Use the split method to cut the string into several strings by a specific character and return the string as an array)
| The Code is as follows: |
Copy code |
|
Var str = "1, 2, 3 ";
StrArr = s. split (","); // separate each comma. |
2. Convert arrays to strings
(Concatenate an array element into a string using a character using the join method)
| The Code is as follows: |
Copy code |
|
Var a = new Array (1, 2, 3 );
Var B = a. join ("-"); |
We do not need to use the above method to convert js arrays and strings.
| The Code is as follows: |
Copy code |
|
Function StringToArray (str, substr ){
/* Function: Splits a string into an Array Based on the specified string.
Parameters:
Str: string to be converted
Substr: Split string
Return Value:
Converted Array
*/
Var arrTmp = new Array ();
If (substr = ""){
ArrTmp. push (str );
Return arrTmp;
}
Var I = 0, j = 0, k = str. length;
While (I <k ){
J = str. indexOf (substr, I );
If (j! =-1 ){
If (str. substring (I, j )! = "") {ArrTmp. push (str. substring (I, j ));}
I = j + 1;
} Else {
If (str. substring (I, k )! = "") {ArrTmp. push (str. substring (I, k ));}
I = k;
}
}
Return arrTmp;
}
Function ArrayToString (arr, str ){
/* Function: convert an array to a string based on the delimiter (string ).
Parameters:
Arr: String Array to be converted
Str: Split string
Return Value:
Converted string
*/
Var strTmp = "";
For (var I = 0; I <arr. length; I ++ ){
If (arr [I]! = ""){
If (strTmp = ""){
StrTmp = arr [I];
} Else {
StrTmp = strTmp + str + arr [I];
}
}
}
Return strTmp;
} |