逃脱字符串拆分&加入

时间:2013-02-05 13:15:22

标签: javascript string split escaping

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

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

以下是一个例子:

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

但是

serialized.split(",")

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

3 个答案:

答案 0 :(得分:3)

您可以改为使用JSON.stringify()JSON.parse()

JSON.stringify(["Hello", ",", "World"]) // -> '["Hello",",","World"]'
JSON.parse('["Hello",",","World"]') // -> ["Hello", ",", "World"]

答案 1 :(得分:1)

手动完成我想出了这个,万一有人再次偶然发现它;)

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);
};

PoC:

serialized = escapeAndJoin(",", ["Hello", ",", "World"]); # -> "Hello,\,,World"
splitAndUnescape(",", serialized) # -> ["Hello", ",", "World"]

答案 2 :(得分:0)

使用特定字符(或句子)加入和分割。

以示例:

["Hello", "," ,"World"].join("*$%").split("*$%")

将返回:

["Hello", "," ,"World"]

不要使用常用字符来分割&amp;加入