1

类似于String split & join,但对于 Javascript:

我有一个字符串数组。我需要能够将这些项目加入一个字符串,然后再次拆分该字符串以获得原始字符串集合。但是,每个字符串也可能包含连接字符串,所以我必须进行一些转义。有没有关于如何实现这一目标的食谱?

这是一个例子:

serialized = ["Hello", ",", "World"].join(",") # Nice would be "Hello,\,,World"

serialized.split(",")

返回["Hello", "", "", "World"]而不是["Hello", ",", "World"]

4

2 回答 2

3

您可以使用JSON.stringify()andJSON.parse()代替。

JSON.stringify(["Hello", ",", "World"]) // -> '["Hello",",","World"]'
JSON.parse('["Hello",",","World"]') // -> ["Hello", ",", "World"]
于 2013-02-05T13:20:17.213 回答
2

手动操作我想出了这个,以防有人再次偶然发现这个;)

splitAndUnescape = function(character, str, opt_escapeChar) {
  var result = [];
  var escapeChar = opt_escapeChar || '\\';
  var tmp = '';
  for (var index = 0; index < str.length; index++) {
    var ch = str.charAt(index);
    if (ch == escapeChar) {
      ch = str.charAt(++index);
    } else if (ch == character) {
      result.push(tmp);
      tmp = '';
      continue;
    }
    tmp += ch;
  }
  if (tmp || result.length) {
    result.push(tmp);
  }
  return result;
};

escapeAndJoin = function(character, array, opt_escapeChar) {
  var escapeChar = opt_escapeChar || '\\';
  var reEscape = new RegExp('(\\' + character + '|\\' + escapeChar + ')', 'g');
  var out = [];
  for (var index = 0; index < array.length; index++) {
    out.push(array[index].replace(reEscape, escapeChar + '$1'));
  }
  return out.join(character);
};

概念验证:

serialized = escapeAndJoin(",", ["Hello", ",", "World"]); # -> "Hello,\,,World"
splitAndUnescape(",", serialized) # -> ["Hello", ",", "World"]
于 2013-02-05T14:53:25.367 回答