JavaScript中的String.replace以反斜杠

时间:2018-06-26 12:25:07

标签: javascript regex

朋友, 这是我的弦。我需要用一些特殊字符替换字符串。

输入:
 '{"country":["US"],"state":["TX"],"Brands":["brd1"," brd12"]}'

输出字符串应为:
"country"=\'US\',"state"=\'TX\',"Brands"=\'brd1, bd2\'

我无法将字符串替换为'\'(反斜杠)。

有人可以帮助我解决此问题吗?

问候 吉里

1 个答案:

答案 0 :(得分:0)

我认为这可能是一个xy问题。无论哪种方式,这里都有一个解决方案:

var str = '{"country":["US"],"state":["TX"],"Brands":["brd1"," brd12", " brd13"]}';

var newStrings = "";

var obj = JSON.parse(str);
var first, mid, last;
first = mid = last = ""

for (k in obj) {
  var pArr = "";
  obj[k].map((o, i) => {
    if (i == 0) first = "'";

    if (i == 0 && i != obj[k].length - 1 || i > 0 && i != obj[k].length - 1) mid = " ,";

    if (i == obj[k].length - 1) last = "'";

    pArr += first + o + mid + last;
    first = "";
    mid = "";
    last = "";
  })

  newStrings += k + "=" + pArr + ","
}

var res = newStrings.replace(/\'/g, "\\'");

console.log(res);//country=\'US\',state=\'TX\',Brands=\'brd1 , brd12 , brd13\',