代码之家  ›  专栏  ›  技术社区  ›  Bromo Programmer

尝试用值替换字符串的一部分时得到System.FormatException

  •  0
  • Bromo Programmer  · 技术社区  · 8 年前

    我有一个javascript文件,它包含下面的JS脚本

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

    我用下面的代码把它读成字符串:

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

    我出错了: 引发异常:mscorlib.dll中的“system.formatException”

    当我试图取代 { 0 } 具有 “我的用户名” . 有人能帮我吗?

    谢谢。

    基于激励方法的回答如下:

    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);
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   PepitoSh    8 年前

    由于您确实必须避开不属于格式的大括号,因此在这种特定情况下,我建议使用另一种方法:

    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);
    
        2
  •  3
  •   Mihail Stancescu    8 年前

    你必须逃离其他一切 { 和 } 只离开 "{0}" 对于 string.format 去工作。

    另外,我将添加一个具有所有变量属性的JS对象,并将其用作JS脚本中的参数或全局对象,因此对于多个脚本,我只需要替换一次值。