Home > Software design >  How does one recognize and/or replace a custom-formatted string value?
How does one recognize and/or replace a custom-formatted string value?

Time:03-12

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

CodePudding user response:

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

CodePudding user response:

From the above comments ...

"Firstly the OP does not work with a json object there is nothing like that. But the OP iterates over the event items of the response object's data-structure. For each item the OP wants to check the property value of item.message.message. Thus the OP's real question is ... 'How does one recognize an emoticon format?'"

The OP might have a look into ... String.prototype.startsWith

// faking the live chat API call for the further example code.

function fetch(/* fake api call url */) {
  return new Promise(resolve => {

    const responseData = '{"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"}';

    setTimeout(() => {
      resolve({ 
        json: () => JSON.parse(responseData),
      });
    }, 4000);
  });
}


const baseUrl = "example.com";

function getEvents(url) {
  console.log(`... fetch('${ url }') ...`);

  fetch(url)
    .then(response => response.json())
    .then(({ events, nextUrl }) => {
      // Process messages of chat events
      events
        .forEach(event => {
          const { method, object: { user, message }, id } = event;

          console.log(`Message event ID: ${ id }`);
          if (
            (method === 'chat') &&
            message.message.startsWith('%%%[emoticon')
          ) {
            // console.log(`${ user.username } sent chat message: ${ message.message }`);

            console.log(`${ user.username } sent chat message: ${ 'Emoticon' }`);

            // // and/or directly overwrite the data
            // message.message = 'Emoticon';            
          } else {
            console.error("Unknown method:", method);
          }
        });
      // Once messages are processed, call `getEvents`
      // again with 'nextUrl' to get new messages.
      getEvents(nextUrl);
    })
    .catch(err => {
      console.error("Error:", err);
    });
}

getEvents(baseUrl);
.as-console-wrapper { min-height: 100%!important; top: 0; }

  • Related