我有一个 XML 文件,其中包含一个简单的节点,例如:
<question lang='en'>Do you want to buy %s from us ?</question>
<question lang='fr'>Voulez-vous acheter chez nous cette %s ?</question>
我有一个 C# 库(使用 ASP.NET),它根据用户语言获取节点值。
我想在 javascript 警报中使用文本
var test = '<%=Language.GetString(Question.EN) %>';
我想通过在 javascript 中调用类似的 sprintf
来在警告对话框中显示以下内容。
或者我必须使用这个插件:http://www.diveintojavascript.com/projects/javascript-sprintf ?
谢谢
最佳答案
您可以使用 String.prototype
将新函数添加到 String
类型 ( JSFiddle demo ):
String.prototype.sprintf = function(){
// if argument list is empty
// return this as new string
if(arguments.length === 0)
return this;
// copy all arguments except the first one
var newArgs = [].slice.call(arguments,1);
// Replace %d, %s, %f, %l, %u with first argument
var tempString = this.replace(/%[dsflu]/,arguments[0]);
// call again until all arguments are used
return tempString.sprintf.apply(tempString,newArgs);
};
var testString = "%s! Do you want to use %s?";
document.write(testString.sprintf("Hello","String.prototype.sprintf"));
关于c# - 在 C# 和 ASP.NET 的 javascript 警报中使用 %s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9733721/