Bromo Programmer
Bromo Programmer

Reputation: 670

I got System.FormatException from trying replacing a part of string with value

I have a javascript file and it contains below js script

(function() {
    try {
        var click = new MouseEvent('click', {bubbles: true, cancelable: true, view: window});
        var field = document.querySelector('input[type="email"]');
        setTimeout(function() {
            field.dispatchEvent(click);
            field.focus();
            field.value="{0}";
        }, 500);
        return true;
    } catch(err) {
        return false; 
    }
})();

And I read that as string using below code:

var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js";
var raw = File.ReadAllText(path);
var args = new object[] { "my_username" };
Console.WriteLine(raw, args);

I got error: Exception thrown: 'System.FormatException' in mscorlib.dll

As I try to replace {0} with "my_username". Can anybody help me?

Thanks.

Answer based on PepitoSh approach is below:

var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js";
var raw = File.ReadAllText(path);
var script = raw.Replace("{0}", "my_username");
Console.WriteLine(script);

Upvotes: 0

Views: 111

Answers (2)

PepitoSh
PepitoSh

Reputation: 1836

Since indeed you have to escape the curly braces that are not part of the formatting, I'd recommend another approach in this specific case:

var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js";
var raw = File.ReadAllText(path);
raw = raw.Replace("{0}", "my_username");
Console.WriteLine(raw);

Upvotes: 2

Mihail Stancescu
Mihail Stancescu

Reputation: 4138

You have to escape all other { and } and leave only "{0}" for the string.format to work.

Also I would add a js object with properties for all variables and use that as an argument or a global object in js scripts, so I only have to replace the values once for multiple scripts.

Upvotes: 3

Related Questions