So, there is a websocket server (game) and requires socket.io messages like this: 42["game:chat-public:msg","{\"id\":\"2qxgs2\",\"pId\":\"nfityk\",\"msg\":\"example\",\"date\":1764384827484}"]. As you see, it's an array but second part of array is backslash escaped json. No direct json allowed in the game.
So i made this to handle it:
const messagePayloadObj = {
msg: msg,
pId: createRandomId()
};
// JSON string
const messagePayloadString = JSON.stringify(messagePayloadObj);
// ESCAPED (Socket.IO expected format)
const escaped = `"${messagePayloadString.replace(/"/g, '\\"')}"`;
if(w.readyState === WebSocket.OPEN){
w.send(`42["game:chat-public:msg",${escaped}]`)
}
It's all okay but some messages that i want to send are ai generated answers and you know, ai answers has backslashes, new line characters etc. (\n). So it's not working in ai generated messages because sent like a string.
How to escape all backslashes includes AI?
"42"+JSON.stringify(["game:chat-public:msg",messagePayloadString]).(?<=(?<!\\)(?:\\\\)*)"[^\\"]*(?:\\[\s\S][^\\"]*)*"regex101.com/r/Ymr0CU/1((?<!\\)(?:\\\\)*)"[^\\"]*(?:\\[\s\S][^\\"]*)*"group1 writeback regex101.com/r/3OfMBF/1(?<=(?<!\\)(?:\\\\)*)"regex101.com/r/zNn7jG/1((?<!\\)(?:\\\\)*)"group1 writeback regex101.com/r/cZ3sZO/1