how to put your text inside backquotes in javascript

Viewed 39

let x = "hello"
console.log(x)
//wanted output `hello` 
//Note i have no control on x i just need to put it inside the `` so that i can make a graphql query
I have a use case where I had a query I need to put that inside the backquotes so that i can make query using graphql.

I have written the query in a separate file because it was taking a lot of space making the code less readable.

5 Answers

You can also use \ before the back quotes like this

let string = "\`Hello\`";
console.log(string)

Here is a functional solution to wrap any string with backticks using a Template literal (note the backticks within the string are escaped):

const x = "hello"

const wrapInBackTicks = (s) => `\`${s}\``

console.log(wrapInBackTicks(x))

This should do it:

let s="hello";
s="`"+s+"`";
console.log(s)

let x = 'hello'
console.log('`'+x+'`')

?

You can use JSON.stringify()

let x = "hello"
console.log(JSON.stringify(x).replace(/"/g,"`"))
//wanted output `hello` 
//Note i have no control on x i just need to put it inside the `` so that i can make a graphql query

Related