首页 > 解决方案 > 搜索字符串的特定部分并将其剪切掉

问题描述

我正在尝试制作一个 discord.js 机器人来检查某个字符串并将其记录在一个 txt 文件中。到目前为止,我有:

  let foundInText = false;
  for (var i in msg) {
    if (message.content.toLowerCase().includes(msg[i].toLowerCase())) foundInText = true;
  }
  if (foundInText) {
    let data=message.content;
    fs.appendFile("saidmessages.txt", `${data}
    `,function(err){
        if(err) throw err;
    });
  }

到目前为止我所拥有的作品。但是,出于我的目的,我只想记录消息的特定部分。目前,它记录了整个消息。有没有办法可以检查特定部分的字符串并只记录字符串的那部分?

标签: stringdiscord.js

解决方案


您正在寻找#includes. 另外,如果您知道字符串是什么,则不必将其剪掉。

let exampleString = "this is a string of words I know";

if (exampleString.split(" ").includes("this")) { //this splits the string into an array, then finds an element that matches "this" and returns a boolean value as to whether it exists
   //use fs to write "this" to the file
}

您可以实现此目的的另一种可能方法是使用Regular Expression

let exampleString = "this is a string of words I know";

var subString = exampleString.replace(new RegExp('.*' + "a"), '');

此正则表达式在某个单词 (/s) 之后剪切文本。
因此,该subString变量将成立string of words I know


推荐阅读