[SOLVED] How does one recognize and/or replace a custom-formatted string value?

Issue

I’m retrieving a JSON-conform data-structure from a live chat API, but when a chat message shows an image the message value shows the url in its own format, embedded in between %%%[ and ]%%%.

The below object gives a preview on what was just described …

{
  events: [{
    method: "chat",
    object: {
      message: {
        bgColor: null,
        color: "#494949",
        font: "default",
        message: "%%%[emoticon name|https://example.org/name.jpg|67|45|/emoticon_report/name/]%%%"
      },
      user: {
        gender: "m",
        username: ""
      }
    },
    id: "text"
  }],
  nextUrl: "text"
}

While processing the above data structure I would like to replace each message value that features the emoticon-format of … %%%[ ... ]%%% … by "Emoticon".

The code I’m working with right now is …

const baseUrl = "example.com"
function getEvents(url) {
    fetch(url).then(response => response.json())
    .then(jsonResponse => {
        // Process messages
        for (const message of jsonResponse["events"]) {
            const method = message["method"]
            const object = message["object"]
            console.log(`Message ID: ${message["id"]}`)
            if (method === "chat") {
                console.log(`${object["user"]["username"]} sent chat message: ${object["message"]["message"]}`)
            } else {
                console.error("Unknown method:", method)
            }
        }

        // Once messages are processed, call getEvents again with 'nextUrl' to get new messages
        getEvents(jsonResponse["nextUrl"])
    })
    .catch(err => {
        console.error("Error:", err)
    })
}

getEvents(baseUrl)

At the moment the script’s result is …

Username: Hi

Username: %%%[emoticon name|https://example.org/name.jpg|67|45|/emoticon_report/name/]%%%

… but it should be changed to …

Username: Hi

Username: Emoticon

Thank you for all the replies, it has helped a lot in figuring out some of the code. I’ve nearly got it done now. The only issue I’m still seeing is if the chat has posted multiple images with a message it cleans the whole message.

For example: Hello this is (image) so try (image) < this only shows Hello this is Emoticon

But I can live with that 😉

The final code that I’ve got includes the following line to clean it up:

var cleanmessage = chat.replace(/%%%\[emoticon.*]%%%/g, `Emoticon`);

Solution

Before using you object["message"]["message"] (or even better just object.message.message) just do a regex replace like this:

object.message.message.replace(/%%%\[emoticon.*]%%%/, 'Emoticon')

playground here : https://regex101.com/r/7Kf0VW/1

Answered By – Michel Lamsoul

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *