如何识别 and/or 替换自定义格式的字符串值?

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

我正在从实时聊天中检索符合 JSON 的数据结构 API,但是当聊天消息显示图像时,message 值显示 url 以其自己的格式嵌入在 %%%[]%%% 之间。

下面的对象预览了刚刚描述的内容...

{
  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"
}

在处理上述数据结构时,我想用 "Emoticon".

替换每个具有... %%%[ ... ]%%% ... 表情符号格式的消息值

我现在使用的代码是...

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)

目前脚本的结果是...

Username: Hi

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

...不过应该改成...

Username: Hi

Username: Emoticon

感谢您的所有回复,它对找出一些代码有很大帮助。我现在差不多完成了。我仍然看到的唯一问题是,如果聊天发布了多张图片和一条消息,它会清除整条消息。

例如:你好,这是(图片)所以尝试(图片)<这只显示你好,这是表情符号

但我可以接受 ;)

我得到的最终代码包括以下行来清理它:

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

从以上评论...

"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?'"

OP 可能会调查... 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; }

在使用对象["message"]["message"](或者更好的只是object.message.message)之前,只需像这样进行正则表达式替换:

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

游乐场在这里:https://regex101.com/r/7Kf0VW/1