1

I have this script in javascript.

    socket.onmessage = function (event) {
        var theDiv = document.getElementById("cli");
        var JSONObject = JSON.parse(event.data);
        if(JSONObject.event === "console output") {
            theDiv.innerHTML += "<div>" + JSONObject['args'] + "</div>";
            
        }
    };

the outcome of JSONObject['args'] is this:

>[2K [16:10:47] [Server thread/INFO]: [Server] test

The string is this

{"event":"console output","args":["\u003e\u001b[2K\r[16:10:47] [Server thread/INFO]: [Server] test"]}

How can i remove this from the string \u003e\u001b[2K\r?

i tried this but it doesn't work

socket.onmessage = function (event) {
        var theDiv = document.getElementById("cli");
        var JSONObject = JSON.parse(event.data.replaceAll("\u003e\u001b[2K\r", ""));
        if(JSONObject.event === "console output") {
            theDiv.innerHTML += "<div>" + JSONObject['args'] + "</div>";

        }
    };

How can I make it work? like this

{"event":"console output","args":["[16:10:47] [Server thread/INFO]: [Server] test"]}
2
  • Can you fix the API? Those codes are to show colors on a terminal, there's no reason to send that in an API. Commented Apr 14, 2021 at 18:46
  • No i can not fix it in the API.. but is it not possible to delete it in string? Commented Apr 14, 2021 at 18:48

2 Answers 2

1

Do the replacement after parsing the JSON.

You need to use map() because JSONObject.args is an array.

theDiv.innerHTML += "<div>" + JSONObject.args.map(arg => arg.replaceAll( "\u003e\u001b[2K\r", "")) + "</div>";

Otherwise you need to escape all the backslashes, so they'll be treated literally.

var JSONObject = JSON.parse(event.data.replaceAll("\\u003e\\u001b[2K\\r", ""));

But it's generally a bad idea to manipulate the JSON string directly, as you may invalidate the JSON. It's usually best to parse the JSON and then deal with the resulting object/array.

Sign up to request clarification or add additional context in comments.

3 Comments

No that is not working ik ge tthis error console:53 Uncaught TypeError: JSONObject.args.replaceAll is not a function at WebSocket.socket.onmessage
It's an array, so you need to map over the elements.
tnx! this is working var JSONObject = JSON.parse(event.data.replaceAll("\\u003e\\u001b[2K\\r", ""));
0

You can try to convert toString() and then remove the value

JSONObject['args'].toString().replace('\u003e\u001b[2K\r', '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.