-6

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?

3
  • 3
    Those are not "AI" generated. They are mearly escape sequences. Commented 17 hours ago
  • Why are you serializing manually? Just do "42"+JSON.stringify(["game:chat-public:msg",messagePayloadString]). Commented 3 hours ago
  • If you just want to escape unescaped or match a string with escaped double quotes, use one of these forms. There are more forms depending on what you need to do. But as of now the question looks to be prematurely closed. (?<=(?<!\\)(?:\\\\)*)"[^\\"]*(?:\\[\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 Commented 15 mins ago

1 Answer 1

-2

Use JSON.stringify() to escape everything.

const escaped = `"${JSON.stringify(messagePayloadString)}"`;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.