Extract variables from text string Javascript

Tags: , ,



I created a Google Slides that contains a lot of variables. I want to be able to pull all variables I have in there at once to Google Sheets. I’m using apps script to get all of the texts as strings from all shapes in the slides.

I have strings that includes both text and variables.

The text contains {{variable1}} and {{variable2}} and also some more {{variable3}}

The desired output is to get an array with all of the variables names.

[variable1, variable2, variable3]

Thanks!

Answer

const input = "The text contains {{variable1}} and {{variable2}} and also some more {{variable3}}"
const regex = /{{(w+)}}/g
const matches = [...input.matchAll(regex)]
console.log(matches.map(([, x]) => x))

Even if you don’t know regexes you can make do with split(). It’s quite hacky though

const input = "The text contains {{variable1}} and {{variable2}} and also some more {{variable3}}"

console.log(input.split('{{').slice(1).map(x => x.split('}}')[0]))


Source: stackoverflow