if(msg.content.includes("[mid]")) {
   let str = msg.content
     let pokeID = str.substring(
       str.indexOf("[mid]") + 5,
       str.lastIndexOf("[/mid") //get the unique-code for a pokemon 

     );
     msg.channel.send({ content: `Here is your Pokemon:`, embeds: [midData(pokeID)] });

这段代码很好用,我可以输入[mid]代码前后的任何用户文本

示例用户输入"此文本可以是任意长度,甚至可以是null[mid]唯一代码[/mid]此文本也可以是任意文本或null"

输出应为:

此文本可以是任意长度,甚至可以为null.此文本也可以是任意文本或null

[mid]唯一代码[mid](这是一个链接)

我试过这个:https://imgur.com/a/uq8CVpn//输出的图像

我需要来自用户输入的3个字符串.

string1=[mid]唯一代码[/mid]//口袋妖怪代码之前的所有文本(如果有)

字符串2=[mid]唯一代码[/mid]

string3=[mid]唯一代码[/mid]//口袋妖怪代码后面的所有文本(如果有)

使用 node v16和discord v13

非常感谢.

推荐答案

您只需要像这样使用lastIndexOfsubstring(我还假设您的意思是在string3中后面,而不是后面):

此外,为了澄清,子字符串的工作方式如下:

substring(startIndex, endIndex /*defaults to the end of the string if not specified*/ )

const message = "this text can be of any length or even null [mid]unique-code[/mid] this text can also be of any text or null"

const beforeCode = message.substring(0, message.lastIndexOf("[mid]")).trim()
const afterCode = message.substring(message.lastIndexOf("[/mid]") + 6).trim()

const code = message.substring(
    message.lastIndexOf("[mid]") + 5, 
    message.lastIndexOf("[/mid]")
).trim();

console.log("beforeCode:", beforeCode, "\nafterCode:", afterCode, "\ncode:", code)

  • 为了在唯一代码之前获得文本,我们将消息从index 0 (the message's start) -> start index of "[mid]"子串

  • 为了获得唯一代码后的文本,我们将消息从end index of "[mid/]" -> end of the string子串

  • 为了获得唯一的代码,我们将消息从end index of "[mid]" -> start index of [mid/]子串

  • 我还使用trim来删除字符串开头或结尾的任何空格

Javascript相关问答推荐

当点击注册页面上的注册按钮时,邮箱重复

如何在 cypress 中使用静态嵌套循环

如何解决useState错误—setSelect Image不是函数''

在JS中拖放:检测文件

在使用HighChats时如何避免Datatables重新初始化错误?

您能在卸载程序(QtInsteller框架)上添加WizardPage吗?

如何在文本字段中输入变量?

使用NextJS+MongoDB+Prisma ORM获取无效请求正文,无法发布错误

是否可以将Select()和Sample()与Mongoose结合使用?

我为什么要使用回调而不是等待?

设置复选框根据选中状态输入选中值

material UI自动完成全宽

在AgGrid中显示分组行的单元格值

根据网络速度加载CS

如何判断字符串是否只包含特定字符串

如何在chartjs-plugin-data Labels v2.1.0插件中设置照片?

从D3 v3更新,没有错误,但输出SVG路径不可见

try 使用Reaction路由V5渲染多个布局

不能用于addEventListener中的变量

promise 封装未知数量的异步工作(即其他promise )