экранировать определенные символы в строке, используя JavaScript - PullRequest
0 голосов
/ 11 октября 2019

У меня есть такая строка:

var str = "[{\"type\": \"text\", \"text\": \"I have below information for you:\"}, {\"type\": \"table\", \"columns\": [\"Product Name\", \"Status\", \"Comments\"], \"rows\": [[\"<button type=\"button\" onclick=\"send('Enfance Flower Detailed Sleeveless Rosette Dress - Maroon ')\">Enfance Flower Detailed Sleeveless Rosette Dress - Maroon</button>\", \"Confirmed\", \"Your order has been verified and you will receive updates when dispatched from our warehouse\"]]}]";

Я хочу заменить все \ "кнопки \" на \\ "кнопки \\", \ "отправить с \\" отправить и) \ "с) \\ "

То, что я до сих пор пробовал: случай 1: заменить \" кнопку \ "на \\" кнопку \\ ":

var str = "[{\"type\": \"text\", \"text\": \"I have below information for you:\"}, {\"type\": \"table\", \"columns\": [\"Product Name\", \"Status\", \"Comments\"], \"rows\": [[\"<button type=\"button\" onclick=\"send('Enfance Flower Detailed Sleeveless Rosette Dress - Maroon ')\">Enfance Flower Detailed Sleeveless Rosette Dress - Maroon</button>\", \"Confirmed\", \"Your order has been verified and you will receive updates when dispatched from our warehouse\"]]}]";

var a = str.replace(/\"button\"/g, '\\\"button\\\"');

console.log(a)

Это дает вывод как

[{"type": "text", "text": "I have below information for you:"}, {"type": "table", "columns": ["Product Name", "Status", "Comments"], "rows": [["<button type=\"button\" onclick="send('Enfance Flower Detailed Sleeveless Rosette Dress - Maroon ')">Enfance Flower Detailed Sleeveless Rosette Dress - Maroon</button>", "Confirmed", "Your order has been verified and you will receive updates when dispatched from our warehouse"]]}]

Вышеуказанный вывод имеет type = \ "button \", следовательно, JSON.parse будет работать в этом.

вариант 2: заменить \ "отправить \ \" отправить

var str = "[{\"type\": \"text\", \"text\": \"I have below information for you:\"}, {\"type\": \"table\", \"columns\": [\"Product Name\", \"Status\", \"Comments\"], \"rows\": [[\"<button type=\"button\" onclick=\"send('Enfance Flower Detailed Sleeveless Rosette Dress - Maroon ')\">Enfance Flower Detailed Sleeveless Rosette Dress - Maroon</button>\", \"Confirmed\", \"Your order has been verified and you will receive updates when dispatched from our warehouse\"]]}]";

var a = str.replace(/\"button\"/g, '\\\"button\\\"');
var a = str.replace(/\"send"/g, '\\\"send');

console.log(a)

Это дает вывод:

[{"type": "text", "text": "I have below information for you:"}, {"type": "table", "columns": ["Product Name", "Status", "Comments"], "rows": [["<button type="button" onclick="send('Enfance Flower Detailed Sleeveless Rosette Dress - Maroon ')">Enfance Flower Detailed Sleeveless Rosette Dress - Maroon</button>", "Confirmed", "Your order has been verified and you will receive updates when dispatched from our warehouse"]]}]

Вышеуказанный вывод даже не содержит отправку type = \ "button \" или \ ". Он удалилescape-символ. Поэтому JSON.parse выдаст ошибку.

case 3: при попытке заменить) \ "на) \\"

var a = str.replace(/)\"/g, ')\\\"');

Выдает ошибку: Uncaught SyntaxError: Invalid regular expression: /)\"/: Unmatched ')'

Ожидаемый конечный вывод:

[{"type": "text", "text": "I have below information for you:"}, {"type": "table", "columns": ["Product Name", "Status", "Comments"], "rows": [["<button type=\"button\" onclick=\"send('Enfance Flower Detailed Sleeveless Rosette Dress - Maroon ')\">Enfance Flower Detailed Sleeveless Rosette Dress - Maroon</button>", "Confirmed", "Your order has been verified and you will receive updates when dispatched from our warehouse"]]}]

Этот конечный вывод будет содержать экранированные двойные кавычки внутри строки, так что он будет работать с JSON.parse.

Howсделать это?

Примечание. Я поставил три косых черты, но понятия не имею, почему один слеш удаляется автоматически.

1 Ответ

2 голосов
/ 11 октября 2019

Просто попробуйте заменить button и send без учета косой черты ранее, и вы получите желаемый результат:

var a = str.replace('"button"', '\\\"button"').replace('"send', '\\\"send');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...