我的msg.text
= /start 76198769
/开始+空格+76198769
如果 msg.text
=/start+76198769 then Temp = 76198769,我如何制定条件?
我是说,我想得到 76198769
await bot.sendMessage(msg.chat.id, `telegram.me/myBot?start=${msg.chat.id}`, opts);
最佳答案
有几种方法可以做到这一点。最简单的可能只是分割你的字符串。
let vals = msg.text.split(' '); // yields an array of '/start', '76198769'
let temp = null;
if(vals[0] === '/start' && vals[1] === '76198769') {
temp = parseInt(vals[1]);
}
或者用正则表达式,你可以做
let matches = /\/start\s(\d+)/g.exec(msg.text);
let temp = null;
if(matches.length) {
temp = parseInt(matches[1]);
}
只是为了好玩,我要指出我在这里推荐的内容也可以扩展。例如,如果您有一个要使用的命令列表,您可以对它们进行测试,然后将命令路由到其他代码。
假设您有“开始”、“停止”、“信息”等命令。如果你像这样创建一个对象(可能通过 Node 中的 require):
const commands = {
'start' : function(args) { /* handle start */},
'stop' : function(args) { /* handle stop */},
'info' : function(args) { /* handle info */}
};
您可以构建您的正则表达式并像这样获取它:
const regex = /\/(start|stop|info)\s(\d+)/g;
let command = null;
let args = null;
let matches = regex.exec(msg.text);
if(matches.length) {
command = matches[1];
args = parseInt(matches[2]);
}
然后您可以使用commands[command](args);
如果您确实需要,您甚至可以通过连接命令对象的键来从字符串构建正则表达式,但我将把它作为练习留给您。 :)
关于javascript - 通过 JavaScript 使用 If Contain Number 创建条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922096/