Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
How does one recognize and/or replace a custom-formatted string value?

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`);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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; }

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!