1

Base on the following string

for(var i=0;i<${MyVar}.length;i++){ alert(${MyVar}[i]); }

How can I remove the ${ at the beginning and end } in the end of string, so it can be used like this?

for(var i=0;i<MyVar.length;i++){ alert(MyVar[i]); }

I'm creating a component in my system to inject javascript code and execute, but i need to replace the system variables to javascript variable.

  var script = document.createElement("script");
  script.innerHTML = "var ... "; // variables
  script.innerHTML += transformCode(code); // code injected
  document.getElementsByTagName("head")[0].append(script);

enter image description here

I already did the part of creating the variables from an array of objects, something like that:

function variableTransform(variables){
  var html = "";
  for(var key in variables) {
    html += "var "+key+" ='"+variables[key]+"';\n";
  }
  //alert(html);
  return html;
}
8
  • 3
    Trying to parse JavaScript code with regex is going to keep you busy. Chances are you will keep finding new patterns where the regex will match too much or too little. Commented Sep 23, 2020 at 21:01
  • So do you have a list of all the variables and their values? There is probably a better way to handle this.... Commented Sep 23, 2020 at 21:10
  • yes, I have all Commented Sep 23, 2020 at 21:11
  • 1
    If you have just the variables by themselves as a string, you could just do replace(/\${|}/g, "") Commented Sep 23, 2020 at 21:14
  • @isherwood I explained up there, I have to create a component that accepts javascript code that will take the system variables and transform it into js code to be executed. Commented Sep 23, 2020 at 21:15

2 Answers 2

4

Use

.replace(/\$\{(\w+)\}/g, '$1')

See proof

Explanation

--------------------------------------------------------------------------------
  \$                       '$'
--------------------------------------------------------------------------------
  \{                       '{'
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                             more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \}                       '}'

JavaScript:

const text = 'for(var i=0;i<${MyVar}.length;i++){ alert(${MyVar}[i]); if(${FooBar}) { ${Bazz}(); } }';
console.log(text.replace(/\$\{(\w+)\}/g, '$1'));

Sign up to request clarification or add additional context in comments.

5 Comments

This is the way to go. I had figured out how to remove the whole var (${myVar}) but I couldn't figure out how to put nyVar back in. But I didn't know about the slick $1. :)
thanks, is to ask to much to remove the "-" in variables? a new scenario appeared.... ${My-Var} to MyVar. thanks again
@sealabr Use /\$\{([\w-]+)\}/g or /\$\{(\w+(?:-\w+)*)\}/g
regex found the occurrence, but not replaced :( :( :( regex101.com/r/njCfKs/1
@sealabr If you need to support one-hyphen variable names, use .replace(/\$\{(\w+)(?:-(\w+))?\}/g, '$1$2'), see regex101.com/r/njCfKs/2. Otherwise, use .replace(/\$\{([\w-]+)\}/g, (_, $1) => $1.replace(/-/g, ''))
0

They are string literals so let it do the work for you.

var variables = 'var FooBar = "Chicken"; var Bazz = "Tuna"; var MyVar = "Dog";';
var codeString = "for(var i=0;i<${MyVar}.length;i++){ alert(${MyVar}[i]); if(${FooBar}) { ${Bazz}(); } }";

var temp = (new Function(variables + " return `" + codeString + "`")());

console.log(temp);

3 Comments

I need to keep the variables and not exchange them for the strings var script = document.createElement("script"); var variables = 'var Bazz = "Tuna";'; var codeString = "alert(${Bazz});"; var temp = (new Function(variables + " return " + codeString + "")()); script.innerHTML += temp; console.log(script.innerHTML); document.getElementsByTagName("head")[0].append(script); ReferenceError: Tuna is not defined
the result: <script>alert(Tuna);</script>
Well that is a bit different that your original idea....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.