Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to replace string in variable with ";"

I believe it's a simple question, but I haven't find a solution and spent a few hours trying to figure up why it's not working.

In a variable I have a string: _webconfig = new Object(); and I want to insert a line after it some text.

I tried to do it with using -replace but it don't work ok, because the function will be 'hitting' more than one time, resulting with the pattern x2.

This is the code I am using now (which don't work) because of the ; in the end of the $pattern variable:

 $Pattern = "_webconfig = new Object();"
 $replaceWith =  "$Pattern `n_webconfig.$key = `"$value`";"       

 # write-Host "Pattern: $Pattern, replaceWith: $replaceWith"
 $text= $text -replace $pattern, $replaceWith
  • the variable $text at the end will be js file, and it needs to have ; at the end of each line.

the result I want to have is:

_webconfig = new Object();

will become:

_webconfig = new Object();
_webconfig.env = "dev";
_webconfig.ServicesAppName= "Services";
  • the 'keys' and 'values' containing the right values.

How can I achieve that?

like image 353
E.Meir Avatar asked Nov 27 '25 13:11

E.Meir


2 Answers

Probably all you have to do is to escape your regex string because of the two parentheses:

$Pattern = "_webconfig = new Object();"
$replaceWith =  "$Pattern `n_webconfig.$key = `"$value`";"       

$text= $text -replace [regex]::Escape($pattern), $replaceWith
like image 168
Martin Brandl Avatar answered Nov 30 '25 04:11

Martin Brandl


If key and value are just strings then use String.Replace:

$Pattern = "_webconfig = new Object();"
$replaceWith =  "$Pattern `n_webconfig.$key = `"$value`";"       

# write-Host "Pattern: $Pattern, replaceWith: $replaceWith"
$text= $text.Replace($pattern, $replaceWith)
like image 35
Andrey Marchuk Avatar answered Nov 30 '25 04:11

Andrey Marchuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!