-1

I want to create a replica of python's f-strings, not for any real reason, only for fun.

What I want:

f`Value of variable: {variable}`

Is there a way to do something like this? (pun intended)

function f(str) {
    return str.replace(/\{(\w+)\}/g, (_, ident) => caller[ident]);
}

No big deal if it isn't possible, I'm just curious.

c8h_
  • 143
  • 1
  • 9
  • Is there a difference to this question? https://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript – A_A Aug 30 '21 at 17:04
  • yes, there is, `arguments.callee.caller` is deprecated and as far as i know, does not return a `this` object. – c8h_ Aug 30 '21 at 17:19

1 Answers1

0

The equivalent of python f-strings already exists in javascript, and it is called template literals. To create a template literal, you would use backticks, and to interpolate values, you use ${} (equivalent of {} in f string in python)

const value = 'World'
console.log(`Hello ${value}!`) // "Hello, World"

As to your other question of how to get the this in the context of where the function was called, you could use the .bind method to bind the function to a certain context. Otherwise, you can also just pass this to the function, which would also work.

More about .bind: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Kenneth Lew
  • 217
  • 3
  • 7
  • i know they exist, i *did* say that i was doing this for fun and not for pracitcal use. – c8h_ Aug 30 '21 at 17:20
  • Oh ok. Well I also just answered you other question about how to bind `this` to a certain context. – Kenneth Lew Aug 30 '21 at 17:22
  • i want the user to call the function using backtick strings, `f\`foo: {bar}\``. i don't see how this would be possible using .bind(), i guess this just isn't possible... – c8h_ Aug 30 '21 at 17:24