javascript里绝对用的上的字符分割函数总结

时间:2022-09-12 17:22:35
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var data = [['your name', 'myvalue'], ['myr name', 'thivalue']];
 
function string_join(data) {
  var str = '', arr = [];
  for (var i = 0; i < data.length; i++) {
   for (var j = 0; j < data[i].length; j++) {
    data[i][j] = slash(data[i][j]);
   }
   arr.push(data[i].join('/'));
  }
  return arr.join(',');
}
 
function slash(string) {
 return String(string).replace(/[\\/,]/g, '\\$&');
}
 
function string_split(string) {
 var c,
   cur_str = '',
   cache = [],
   result = [];
 for (var i = 0; i < string.length; i++) {
  c = string.charAt(i);
  switch(c) {
   case '\\':
    cur_str += string.charAt(++i);
    break;
   case '/':
    cache.push(cur_str);
    cur_str = '';
    break;
   case ',':
    cache.push(cur_str);
    cur_str = '';
    result.push(cache);
    cache = [];
    break;
   default:
    cur_str += c;
  }
 }
 
 if (cur_str.length) {
  cache.push(cur_str);
 }
 
 if (cache.length) {
  result.push(cache);
 }
 
 return result;
}
 
var before = string_join(data);
console.log(before);
var after = string_split(before);
console.log(after);