Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在JavaScript中使用String.Format?_C#_.net_Javascript - Fatal编程技术网

C# 在JavaScript中使用String.Format?

C# 在JavaScript中使用String.Format?,c#,.net,javascript,C#,.net,Javascript,这让我快发疯了。我相信我问了完全相同的问题,但我再也找不到了(我使用了StackOverflow搜索、Google搜索、手动搜索我的帖子和搜索我的代码) 我想要一些类似于C#String.Format的东西,在这里你可以做类似的事情 string format = String.Format("Hi {0}",name); 当然,就JavaScript而言,一个人给了我一个简单的答案,它不像jQuery插件或任何东西,但我认为你做了一些JSON之类的东西,它工作正常,使用简单 我一生都找不到这

这让我快发疯了。我相信我问了完全相同的问题,但我再也找不到了(我使用了StackOverflow搜索、Google搜索、手动搜索我的帖子和搜索我的代码)

我想要一些类似于C#String.Format的东西,在这里你可以做类似的事情

string format = String.Format("Hi {0}",name);
当然,就JavaScript而言,一个人给了我一个简单的答案,它不像jQuery插件或任何东西,但我认为你做了一些JSON之类的东西,它工作正常,使用简单

我一生都找不到这个职位

我的代码中确实有这一点,但我似乎找不到任何使用它的东西,我非常确定我已经使用过几次了:

String.prototype.format = function(o)
{
    return this.replace(/{([^{}]*)}/g,
       function(a, b)
       {
           var r = o[b];
           return typeof r === 'string' ? r : a;
       }
    );
};

没有第三方职能:

string format = "Hi {0}".replace('{0}', name)
具有多个参数:

string format = "Hi {0} {1}".replace('{0}', name).replace('{1}', lastname)

您可以这样做一系列替换:

function format(str)
{
    for(i = 1; i < arguments.length; i++)
    {
        str = str.replace('{' + (i - 1) + '}', arguments[i]);
    }
    return str;
}
通过这种方式,您可以同时提供索引和命名参数:

var arr = ['0000', '1111', '2222']

arr.a = 'aaaa'

str = format(" { 0 } , {1}, { 2}, {a}", arr)
// returns 0000 , 1111, 2222, aaaa
修改源代码

只要删除所有的
\u validateParams
代码,就可以在JavaScript中创建一个成熟的.NET字符串类

好的,我解放了msajax字符串类,删除了所有msajax依赖项。它工作得很好,就像.NET字符串类一样,包括trim函数、endsWith/startsWith等

另外,我将所有VisualStudioJavaScript IntelliSense助手和XmlDocs保留在适当的位置。如果不使用VisualStudio,它们是无害的,但是如果愿意,可以删除它们

<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
    var a = String.format("Hello {0}!", "world");
    alert(a);

</script>

var a=String.format(“Hello{0}!”,“world”);
警报(a);
String.js
//String.js-由Sky Sanders于2010年3月28日从MicrosoftAjax.js中解放出来
//permalink:http://stackoverflow.com/a/2534834/2343
/*
版权所有(C)2009,CODULTEX基金会
版权所有。
允许以源代码和二进制形式重新分发和使用,无论是否修改
但须符合下列条件:
*源代码的重新分发必须保留上述版权声明、此条件列表
以及以下免责声明。
*以二进制形式重新分发时,必须复制上述版权声明、此条件列表
以及随分发提供的文档和/或其他材料中的以下免责声明。
*无论是CODULTEX基金会的名称,还是其贡献者的姓名,都不可用于背书或
未经事先书面许可,促销源自本软件的产品。
本软件由版权所有者和贡献者按原样以及任何明示或暗示的方式提供
保证,包括但不限于适销性和适用性的默示保证
不承认有特定目的。在任何情况下,版权所有人或贡献者概不负责
任何直接、间接、附带、特殊、惩戒性或后果性损害(包括但不限于
仅限于,替代商品或服务的采购;使用、数据或利润的损失;或业务损失
中断)无论是何种原因造成的,且基于任何责任理论,无论是在合同中,还是在严格责任中,
或因使用本软件而产生的侵权行为(包括疏忽或其他),甚至
如果告知可能发生此类损坏。
*/
(功能(窗口){
$type=字符串;
$type.\uuuTypeName='String';
$type.\uu class=true;
$prototype=$type.prototype;
$prototype.endsWith=函数字符串$endsWith(后缀){
///确定此实例的结尾是否与指定的字符串匹配。
///要比较的字符串。
///如果后缀匹配此实例的结尾,则为true;否则为false。
返回(this.substr(this.length-suffix.length)==后缀);
}
$prototype.startsWith=函数字符串$startsWith(前缀){
///确定此实例的开头是否与指定的字符串匹配。
///要比较的字符串。
///如果前缀匹配此字符串的开头,则为true;否则为false。
返回(this.substr(0,prefix.length)==前缀);
}
$prototype.trim=函数字符串$trim(){
///从当前字符串对象中删除所有前导和尾随空格字符。
///从当前字符串对象的开头和结尾删除所有空白字符后保留的字符串。
返回此。替换(/^\s+|\s+$/g,');
}
$prototype.trimEnd=函数字符串$trimEnd(){
///从当前字符串对象中删除所有尾随空格。
///从当前字符串对象的末尾删除所有空白字符后保留的字符串。
返回此。替换(/\s+$/,“”);
}
$prototype.trimStart=函数字符串$trimStart(){
///从当前字符串对象中删除所有前导空格。
///从当前字符串对象的开头删除所有空白字符后保留的字符串。
返回此。替换(/^\s+/,“”);
}
$type.format=函数字符串$format(格式,args){
///将指定字符串中的格式项替换为相应对象实例值的文本等效项。不变区域性将用于格式化日期和数字。
///格式字符串。
///要格式化的对象。
///格式的副本,其中格式项已被对象参数的相应实例的等效字符串替换。
返回字符串.tofu-formattedString(false,参数);
}
$type.\u-toFormattedString=函数字符串$\u-toFormattedString(useLocale,args){
var结果=“”;
var format=args[0];
对于(变量i=0;;){
//查找下一个打开或关闭的大括号
var open=format.indexOf('{',i);
var close=format.indexOf('}',i);
如果((打开<0)和&(关闭<0)){
//未找到:复制字符串的结尾并断开
<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
    var a = String.format("Hello {0}!", "world");
    alert(a);

</script>
// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
// permalink: http://stackoverflow.com/a/2534834/2343

/*
    Copyright (c) 2009, CodePlex Foundation
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted
    provided that the following conditions are met:

    *   Redistributions of source code must retain the above copyright notice, this list of conditions
        and the following disclaimer.

    *   Redistributions in binary form must reproduce the above copyright notice, this list of conditions
        and the following disclaimer in the documentation and/or other materials provided with the distribution.

    *   Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
        promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
    IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
*/

(function(window) {

    $type = String;
    $type.__typeName = 'String';
    $type.__class = true;

    $prototype = $type.prototype;
    $prototype.endsWith = function String$endsWith(suffix) {
        /// <summary>Determines whether the end of this instance matches the specified string.</summary>
        /// <param name="suffix" type="String">A string to compare to.</param>
        /// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
        return (this.substr(this.length - suffix.length) === suffix);
    }

    $prototype.startsWith = function String$startsWith(prefix) {
        /// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
        /// <param name="prefix" type="String">The String to compare.</param>
        /// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
        return (this.substr(0, prefix.length) === prefix);
    }

    $prototype.trim = function String$trim() {
        /// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
        return this.replace(/^\s+|\s+$/g, '');
    }

    $prototype.trimEnd = function String$trimEnd() {
        /// <summary >Removes all trailing white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
        return this.replace(/\s+$/, '');
    }

    $prototype.trimStart = function String$trimStart() {
        /// <summary >Removes all leading white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
        return this.replace(/^\s+/, '');
    }

    $type.format = function String$format(format, args) {
        /// <summary>Replaces the format items in a specified String with the text equivalents of the values of   corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
        /// <param name="format" type="String">A format string.</param>
        /// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
        /// <returns type="String">A copy of format in which the format items have been replaced by the   string equivalent of the corresponding instances of object arguments.</returns>
        return String._toFormattedString(false, arguments);
    }

    $type._toFormattedString = function String$_toFormattedString(useLocale, args) {
        var result = '';
        var format = args[0];

        for (var i = 0; ; ) {
            // Find the next opening or closing brace
            var open = format.indexOf('{', i);
            var close = format.indexOf('}', i);
            if ((open < 0) && (close < 0)) {
                // Not found: copy the end of the string and break
                result += format.slice(i);
                break;
            }
            if ((close > 0) && ((close < open) || (open < 0))) {

                if (format.charAt(close + 1) !== '}') {
                    throw new Error('format stringFormatBraceMismatch');
                }

                result += format.slice(i, close + 1);
                i = close + 2;
                continue;
            }

            // Copy the string before the brace
            result += format.slice(i, open);
            i = open + 1;

            // Check for double braces (which display as one and are not arguments)
            if (format.charAt(i) === '{') {
                result += '{';
                i++;
                continue;
            }

            if (close < 0) throw new Error('format stringFormatBraceMismatch');


            // Find the closing brace

            // Get the string between the braces, and split it around the ':' (if any)
            var brace = format.substring(i, close);
            var colonIndex = brace.indexOf(':');
            var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;

            if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');

            var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);

            var arg = args[argNumber];
            if (typeof (arg) === "undefined" || arg === null) {
                arg = '';
            }

            // If it has a toFormattedString method, call it.  Otherwise, call toString()
            if (arg.toFormattedString) {
                result += arg.toFormattedString(argFormat);
            }
            else if (useLocale && arg.localeFormat) {
                result += arg.localeFormat(argFormat);
            }
            else if (arg.format) {
                result += arg.format(argFormat);
            }
            else
                result += arg.toString();

            i = close + 1;
        }

        return result;
    }

})(window);
"Hello {0},".format(["Bob"]);
function format(string, object) {
    return string.replace(/{([^{}]*)}/g,
       function(match, group_match)
       {
           var data = object[group_match];
           return typeof data === 'string' ? data : match;
       }
    );
}
string format = "Hi {foo}".replace({
    "foo": "bar",
    "fizz": "buzz"
});
var r = o[b];
  String.format = function() {
      var s = arguments[0];
      for (var i = 0; i < arguments.length - 1; i++) {       
          var reg = new RegExp("\\{" + i + "\\}", "gm");             
          s = s.replace(reg, arguments[i + 1]);
      }
      return s;
  }
var greeting = String.format("Hi, {0}", name);
// --------------------------------------------------------------------
// Add prototype for 'String.format' which is c# equivalent
//
// String.format("{0} i{2}a night{1}", "This", "mare", "s ");
// "{0} i{2}a night{1}".format("This", "mare", "s ");
// --------------------------------------------------------------------

if(!String.format)
    String.format = function(){
        for (var i = 0, args = arguments; i < args.length - 1; i++)
            args[0] = args[0].replace("{" + i + "}", args[i + 1]);
        return args[0];
    };
if(!String.prototype.format && String.format)
    String.prototype.format = function(){
        var args = Array.prototype.slice.call(arguments).reverse();
        args.push(this);
        return String.format.apply(this, args.reverse())
    };
(function () {
    if (!String.prototype.format) {
        var regexes = {};
        String.prototype.format = function (parameters) {
            for (var formatMessage = this, args = arguments, i = args.length; --i >= 0;)
                formatMessage = formatMessage.replace(regexes[i] || (regexes[i] = RegExp("\\{" + (i) + "\\}", "gm")), args[i]);
            return formatMessage;
        };
        if (!String.format) {
            String.format = function (formatMessage, params) {
                for (var args = arguments, i = args.length; --i;)
                    formatMessage = formatMessage.replace(regexes[i - 1] || (regexes[i - 1] = RegExp("\\{" + (i - 1) + "\\}", "gm")), args[i]);
                return formatMessage;
            };
        }
    }
})();
public static string Format(
    string format,
    params Object[] args
)
var StringHelpers = {
    format: function(format, args) {
        var i;
        if (args instanceof Array) {
            for (i = 0; i < args.length; i++) {
                format = format.replace(new RegExp('\\{' + i + '\\}', 'gm'), args[i]);
            }
            return format;
        }
        for (i = 0; i < arguments.length - 1; i++) {
            format = format.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i + 1]);
        }
        return format;
    }
};
StringHelpers.format("{0}{1}", "a", "b")
StringHelpers.format("{0}{1}", ["a", "b"])
function format(str, args) {
   for (i = 0; i < args.length; i++)
      str = str.replace("{" + i + "}", args[i]);
   return str;
}
function format (fmtstr) {
  var args = Array.prototype.slice.call(arguments, 1);
  return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
    return args[index];
  });
}
var str = format('{0}, {1}!', 'Hello', 'world');
console.log(str); // prints "Hello, world!"
var str = format('{1}, {0}!', 'Hello', 'world');
console.log(str); // prints "world, Hello!"
String.prototype.format = function() {
    var s = this;
    for (var i = 0; i < arguments.length; i++) {       
        var reg = new RegExp("\\{" + i + "\\}", "gm");             
        s = s.replace(reg, arguments[i]);
    }
    return s;
}
StringFormat.format("Hi %s, I like %s", ["Rob", "icecream"]);
Hi Rob, I like icecream.
StringFormat.format("Duke's Birthday: %1$tA %1$te %1$tB, %1$tY", [new Date("2014-12-16")]);

Duke's Birthday: Tuesday 16 December, 2014
if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
              ? args[number]
              : match
            ;
        });
    };
}
'{0}-{1}'.format('a','b');
// Result: 'a-b'
function stringFormat(str) {
  if (str !== undefined && str !== null) {
    str = String(str);
    if (str.trim() !== "") {
      var args = arguments;
      return str.replace(/(\{[^}]+\})/g, function(match) {
        var n = +match.slice(1, -1);
        if (n >= 0 && n < args.length - 1) {
          var a = args[n + 1];
          return (a !== undefined && a !== null) ? String(a) : "";
        }
        return match;
      });
    }
  }
  return "";
}

alert(stringFormat("{1}, {0}. You're looking {2} today.",
  "Dave", "Hello", Math.random() > 0.5 ? "well" : "good"));
var customer = { name: "Foo" }
var card = { amount: 7, product: "Bar", unitprice: 42 }
var message = `Hello ${customer.name},
               want to buy ${card.amount} ${card.product} for
               a total of ${card.amount * card.unitprice} bucks?`
//Add "format" method to the string class
//supports:  "Welcome {0}. You are the first person named {0}".format("David");
//       and "First Name:{} Last name:{}".format("David","Wazy");
//       and "Value:{} size:{0} shape:{1} weight:{}".format(value, size, shape, weight)
String.prototype.format = function () {
    var content = this;
    for (var i = 0; i < arguments.length; i++) {
        var target = '{' + i + '}';
        content=content.split(target).join(String(arguments[i]))
        content = content.replace("{}", String(arguments[i]));
    }
    return content;
}
alert("I {} this is what {2} want and {} works for {2}!".format("hope","it","you"))
String.prototype.format = function () {
    var formatted = this;
    for (var arg in arguments) {
        formatted = formatted.split('{' + arg + '}').join(arguments[arg]);
    }
    return formatted;
};