简体   繁体   English

正则表达式替换引号之间的值

[英]Regex to replace a value between quotes

Im trying to replace 2 variable values in a file. 我试图替换文件中的2个变量值。 I read the file contents in nodejs into a string. 我将nodejs中的文件内容读入一个字符串。 And I need to search for these variables and replace their values. 我需要搜索这些变量并替换它们的值。

original string 原始字符串

var useStub = false;var serviceUrl = 'http://servicetest.test.com';

I want to run some sort of command like 我想运行某种命令

var result = someFile.replace(regex, 'http://servicestage.stage.com');
var result = someFile.replace(regex, 'true');

After this command I want the output like 在这个命令后,我希望输出像

var useStub = true;var serviceUrl = 'http://servicestage.stage.com';    

I tried a couple of regex patterns but it didnt get the output I need. 我尝试了几个正则表达式模式,但它没有得到我需要的输出。 I have very little exp with regexes. 我有很少的exp与正则表达式。 Can someone help me with this? 有人可以帮我弄这个吗?


Got it working finally with help from @FloatingCoder. 最后在@FloatingCoder的帮助下完成了工作。

var text = "var useStub=false;var serviceUrl='http://servicetest.test.com';var hello='sdfdsfs';";
text = text.replace(/var serviceUrl='.*?';/, "var serviceUrl='http://newurl.test.com';");
text = text.replace(/var useStub=.*?;/, "var useStub=true;");
console.info(text);

Here is the fiddle for others 这是别人的小提琴

Try this... 尝试这个...

var text = "var useStub = false;var serviceUrl = 'http://servicetest.test.com';";

text = text.replace(/var serviceUrl = '.*?';/, "var serviceUrl = 'http://newurl.test.com';");
text = text.replace(/var useStub = .*?;/, "var useStub = true;");

document.getElementById("output").innerHTML = text;

This might need more tweaking, depending on what else is in the file, but from what you've given, this will work. 这可能需要更多调整,具体取决于文件中的其他内容,但是根据您的指示,这将起作用。

There's a JSFiddle to play with here . 有一个的jsfiddle一起玩在这里

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

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