string - 搜索字符串的特定部分并将其剪切掉
问题描述
我正在尝试制作一个 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;
});
}
到目前为止我所拥有的作品。但是,出于我的目的,我只想记录消息的特定部分。目前,它记录了整个消息。有没有办法可以检查特定部分的字符串并只记录字符串的那部分?
解决方案
您正在寻找#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
。
推荐阅读
- python - C# 代码移植到 Python 的结果不一样
- javascript - 我的脚本目前给我的问题是它没有显示用户在网页上添加的输入?
- python - 如何在python中格式化字符串
- java - 凌空到Android Studio中的Json错误
- c++ - 无法对向量进行排序
> - javascript - node_modules 位于不同目录时如何运行单元测试
- javascript - JavaScript 用多个引号和不同的 ID 分割字符串
- javascript - 有没有办法通过点击线来改变高图的颜色
- webpack - webpack next.js TypeError:“原始”参数必须是函数类型
- python-3.x - 实施 celery 搞砸了我的 INSTALLED_APPS (ModuleNotFoundError: No module named myapp)