Home >Web Front-end >JS Tutorial >Summary of character splitting functions that are absolutely useful in javascript_javascript skills

Summary of character splitting functions that are absolutely useful in javascript_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 16:40:421468browse
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);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn