的String.Format在JavaScript? [英] String.Format in javascript?

查看:193
本文介绍了的String.Format在JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我发疯。我相信,我问这个完全一样的问题,但我无法找到它了(我用计算器搜索,谷歌搜索,手动搜索我的职位,我的搜索​​code)。

我想要的东西,这将是像C#的String.Format,你可以不喜欢

字符串格式=的String.Format(嗨{0},名称);

只是场和一个人的JavaScript给了我一个简单的回答这是不是像一个jQuery插件或什么,但我认为你做了一些JSON的事情或东西,它的工作和简单易用。

我为我的生活不能找到这个帖子。

我做我的code有这个,但我似乎无法找到使用它的任何东西,我是pretty的肯定,我用它几次。

  String.prototype.format =功能(O)
{
    返回this.replace(/ {([^ {}] *)} /克,
       功能(A,B)
       {
           变种R =的问题o [B];
           返回的typeof  -  [R ===字符串? R:A;
       }
    );
};
 

解决方案

从适应code <一个href="http://ajaxcontroltoolkit.$c$cplex.com/SourceControl/latest#Client/MicrosoftAjax/Extensions/String.js">MsAjax字符串。

只是删除​​所有的 _validateParams code和你最的方式在JavaScript中一个完全成熟的.NET string类。

好吧,我解放了msajax串类,删除所有msajax依赖。伟大的作品,就像.NET串类,包括修剪功能和的endsWith / startsWith等。

P.S。 - 我将所有的Visual Studio的JavaScript智能感知佣工及XmlDocs到位。他们是无害的,如果你不使用Visual Studio,但你可以删除它们,如果你喜欢。

 &LT;脚本SRC =脚本/ string.js类型=文/ JavaScript的&GT;&LT; / SCRIPT&GT;
&LT;脚本类型=文/ JavaScript的&GT;
    VAR一个=的String.Format(你好{0}!,世界);
    警报(一);

&LT; / SCRIPT&GT;
 

String.js

  // String.js  - 由天空桑德斯从MicrosoftAjax.js解放上03/28/10
//永久链接:http://stackoverflow.com/a/2534834/2343

/ *
    版权所有(C)2009,codePLEX基金会
    版权所有。

    再分配和在源代码和二进制形式使用,无论修改与否,是允许的
    只要符合下列条件:

    *源$ C ​​$ C再分发必须保留以上版权声明,本文所列条件
        和下面的免责声明。

    *以二进制形式重新分发必须复制上述版权声明,此条件列表
        和文档和/或其他材料中的下列免责条款在分发提供。

    *无论是codePLEX基金会及其贡献者的名字的名字可以用来支持或
        促进衍生自该软件,而无需事先书面许可产品。

    本软件由版权所有者和贡献者按原样,并且没有任何EX $ P $干燥综合征或暗示的保证
    的担保,包括但不限于适销性和适用性的暗示担保
    特定用途的适用性。在任何情况下,著作权人或者投资方都不
    对任何直接,间接,偶然,特殊,惩戒性,或者后果性损害(包括但
    仅限于购买替代商品或服务;使用,数据,或利润损失;或业务
    中断)造成的,基于何种责任理论,无论是合同,严格责任,
    还是侵权(包括疏忽或其他原因)承担任何责任出这个软件的使用,即使
    已被告知发生此类损害与LT的可能性; / textarea的&GT;
* /

(函数(窗口){

    $类型=字符串;
    $型.__的typeName ='字符串';
    $型.__类= TRUE;

    $样机= $ type.prototype;
    $ prototype.endsWith =功能字符串$的endsWith(后缀){
        ///&LT;总结&gt;确定此实例的结尾是否与指定的字符串匹配&LT; /总结&gt;
        ///&LT; PARAM NAME =后缀类型=字符串&GT; A字符串​​比较上述&lt; /参数&GT;
        ///&LT;返回TYPE =布尔&GT;真,如果后缀此实例的结尾相匹配;否则为false&LT; /回报&GT;
        返程(this.substr(this.length  -  suffix.length)===后缀);
    }

    $ prototype.startsWith =功能字符串$ startsWith(preFIX){
        ///&LT;总结&gt;确定此实例的开头是否与指定的字符串匹配&LT; /总结&gt;
        ///&LT; PARAM NAME =preFIX类型=字符串&GT;比较字符串&LT; /参数&GT;
        ///&LT;返回TYPE =布尔&GT;真,如果preFIX该字符串的开头相匹配;否则为false&LT; /回报&GT;
        返回(this.substr(0,prefix.length)=== preFIX);
    }

    $ prototype.trim =功能字符串$ TRIM(){
        ///&LT;总结&gt;删除所有的开头和结尾的空白字符从当前String对象&LT; /总结&gt;
        ///&LT;返回一个类型=字符串&GT;剩下毕竟空白字符从一开始就和当前String对象的末尾删除字符串&LT; /回报&GT;
        返回this.replace(/ ^ \ S + | \ s + $ /克,'');
    }

    $ prototype.trimEnd =功能字符串$ trimEnd(){
        ///&LT;总结&gt;删除所有尾随空格从当前String对象&LT; /总结&gt;
        ///&LT;返回一个类型=字符串&GT;剩下毕竟空白字符是从当前String对象的末尾删除字符串&LT; /回报&GT;
        返回this.replace(/ \ S + $ /,'');
    }

    $ prototype.trimStart =功能字符串$ trimStart(){
        ///&LT;总结&gt;删除所有前导空格从当前String对象&LT; /总结&gt;
        ///&LT;返回一个类型=字符串&GT;剩下毕竟空白字符是从当前String对象的开始删除字符串&LT; /回报&GT;
        返回this.replace(/ ^ \ S + /,'');
    }

    $ type.format =功能字符串$格式(格式参数){
        ///&LT;总结&gt;替换与相应的对象实例的值的文本对应一个指定的字符串格式项。固定区域性将用于格式化日期和数字&LT; /总结&gt;
        ///&LT; PARAM NAME =格式类型=字符串&gt;在格式字符串&LT; /参数&GT;
        ///&LT; PARAM NAME =的argsparameterArray =真正的MAYBENULL =真&gt;将对象格式化&LT; /参数&GT;
        ///&LT;返回一个类型=字符串&GT;的格式,其中的格式项已被取代的等效字符串对象参数对应的实例474上的副本; /回报&GT;
        返回String._toFormattedString(假,参数);
    }

    $ type._toFormattedString =功能字符串$ _toFormattedString(useLocale,参数){
        VAR的结果='';
        变种格式=的args [0];

        为(变种I = 0;){
            //查找下开启或关闭大括号
            VAR开= format.indexOf('{',我);
            VAR接近= format.indexOf('}',我);
            如果((开放℃,)及及(靠近℃,)){
                //未找到:复制字符串和突破的结束
                结果+ = format.slice(ⅰ);
                打破;
            }
            如果((接近大于0)及及((接近&所述;开放)||(开放℃,))){

                如果(format.charAt(接近+ 1)!=='}'){
                    抛出新的错误(格式stringFormatBraceMismatch');
                }

                结果+ = format.slice(ⅰ,靠近+ 1);
                I =关闭+ 2;
                继续;
            }

            //支架前的字符串拷贝
            结果+ = format.slice(I,开启);
            I =开+ 1;

            //检查双括号(它显示为一体,并没有参数)
            如果(format.charAt(ⅰ)==='{'){
                结果+ ='{';
                我++;
                继续;
            }

            如果(接近℃的)抛出新的错误(格式stringFormatBraceMismatch');


            //找到右大括号

            //获取括号内的字符串,并围绕它分割':'(如果有的话)
            VAR括号= format.substring(我和关闭);
            VAR colonIndex = brace.indexOf(:);
            变种argNumber = parseInt函数((colonIndex℃,)支撑:brace.substring(0,colonIndex),10)+ 1;

            如果(isNaN(argNumber))抛出新的错误(格式stringFormatInvalid');

            变种argFormat =(colonIndex℃,)? '':brace.substring(colonIndex + 1);

            VAR ARG =的args [argNumber]
            如果(typeof运算(ARG)===未定义|| ARG === NULL){
                ARG ='';
            }

            //如果它有一个toFormattedString方法,调用它。否则,调用toString()
            如果(arg.toFormattedString){
                结果+ = arg.toFormattedString(argFormat);
            }
            否则,如果(useLocale&安培;&安培; arg.localeFormat){
                结果+ = arg.localeFormat(argFormat);
            }
            否则,如果(arg.format){
                结果+ = arg.format(argFormat);
            }
            其他
                结果+ = arg.toString();

            I =关闭+ 1;
        }

        返回结果;
    }

})(窗口);
 

this is driving me nuts. I believe I asked this exact same question but I can't find it anymore(I used stackoverflow search, google search, manually searched my posts, searched my code).

I wanted something that would be like the C# String.Format where you could do something like

string format = String.Format("Hi {0}",name);

just for javascript of course and one person gave me a simple answer it was not like a jquery plugin or anything but I think you made some json thing or something and it worked and was simple to use.

I for the life of me can't find this post.

I do have this in my code but I can't seem to find anything that uses it and I am pretty sure I used it a couple times.

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

解决方案

Adapt the code from MsAjax string.

Just remove all of the _validateParams code and you are most of the way to a full fledged .net string class in javascript.

Okay, I liberated the msajax string class, removing all the msajax dependencies. Works great, just like .net string class, including trim functions and endsWith/startsWith etc.

P.S. - I left all of the Visual Studio JavaScript intellisense helpers and XmlDocs in place. They are innocuous if you don't use visual studio but you can remove them if you like.

<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

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

这篇关于的String.Format在JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆