简体   繁体   English

Javascript正则表达式删除开头和结尾的特定字符串

[英]Javascript regex to remove Specific strings in beginning and end

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.我正在我的系统中创建一个组件来注入 javascript 代码并执行,但我需要将系统变量替换为 javascript 变量。

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

在此处输入图片说明

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;
}

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: JavaScript:

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

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM