2

I want to be able to return the content of these variables by using regular expressions.

'use strict'

const Telegraf = require('telegraf')
const fs = require('fs')

var ar1 = fs.readFileSync('folder/ar1.txt').toString()
var ar2 = fs.readFileSync('folder/ar2.txt').toString()
var ar3 = fs.readFileSync('folder/ar3.txt').toString()

I tried using:

app.hears(/\bar\d/i, (ctx) => {
    ctx.reply(ctx.match[0])
    //Returns: "ar1"
})

But this only returns the string, not the content of the variable.

  • Did you try `match[1]`? https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression – CAustin Nov 13 '17 at 19:55

1 Answers1

0

You could use eval here, but I don't suggest it. Instead, I suggest you map your variables.

const files = {
    "ar1" : fs.readFileSync('folder/ar1.txt').toString(),
    "ar2" : fs.readFileSync('folder/ar2.txt').toString(),
    "ar3" : fs.readFileSync('folder/ar3.txt').toString()
};

Then, you can use your found string to reply with your object key (a Map can also be used here)

app.hears(/\b(a+)r\d/i, (ctx) => {
    ctx.reply(files[ctx.match[0]]);
    //now returns the file
});
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118