String.Format in javascript
有些时候,我们确实需要在JavaScript中进行字符串替换,类似于C#中的String.Format()方法一样,只不过这种格式化替换只局限于对由'{0}','{1}','{2}'...所组成的“占位符”进行字符串替换,而并不会像C#中可以进行字符串格式化替换。这会大量简化我们的代码,使得程序结构变得更加清晰。众所周知,JavaScript中的replace方法默认只能对第一个匹配到的字符串进行替换,如果给定的字符串中存在多个匹配项,则除了第一个匹配项之外其余的部分都不会被替换。因此我们可以借助于正则表达式来进行替换。
来看看下面这个方法:
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} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET");
ASP is dead, but ASP.NET is alive! ASP {2}
注意'{2}'没有被替换,因为参数列表中没有给定对应的值。在该方法中,没有对参数列表和占位符进行严格限制。也就是说,允许占位符中的数字不连续或者一定要从0开始,而且参数列表的数量并不一定要与占位符中的数字完全对应。只对正则表达式匹配到的项进行查找替换。所以该方法可以满足一些基本应用。
这里还有另外一个JavaScript类库。
// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders /*
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.js
<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
var a = String.format("Hello {0}!", "world");
alert(a); </script>
另外,我的另一篇博客中有关于如何在JavaScript中对字符串进行Trim操作的例子:
http://www.cnblogs.com/jaxu/archive/2009/03/12/1409395.html
String.Format in javascript的更多相关文章
- JavaScript string.format
//string.format String.prototype.format=function(){ var e = this, f = arguments.length; if (f > 0 ...
- 编写javascript、Jquery的String.format();
在javascript.Jquery里面好像是没有String.format();这个函数的,所以我们在拼接字符串的时候就特别的辛苦,生怕又打错,而且又乱,所以就自己去写一个函数来代替. String ...
- javascript版string.Format
原文发布时间为:2011-03-28 -- 来源于本人的百度文章 [由搬家工具导入] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tran ...
- Javascript中的String.format方法实现
<script type='text/javascript'> String.format = function() { var s = arguments[0]; for (var i ...
- Java 和JavaScript实现C#中的String.format效果
1.Java实现 /** * 需要引入com.alibaba.fastjson.1.2.8 * String result2=HuaatUtil.format(templa ...
- javascript js string.Format()收集
方案1http://www.cnblogs.com/loogn/archive/2011/06/20/2085165.html String.prototype.format = function(a ...
- string.Format 里面包含 javascript方法参数的时候 单引号变成双引号的问题解决方法
解决方法如下 StringBuilder sb = new StringBuilder(); var str =@"<label><input type='checkbox ...
- try { var mergeFilePath = string.Format("{0}mergepdf.pdf", tempDownDir); PDFPrintHelper.MergePDFFile(pdfList, mergeFi
winform 按顺序连续打印多个PDF文件 关于PDF打印的问题,前面有篇文章(点这里查看)也叙述过,今天来谈谈另外一种方法 其实方法很简单,因为需要把多个PDF文档按顺序连续打印,为此我们为什 ...
- (转)使用string.Format需要注意的一个性能问题
今天,我在写C#代码时,突然发现一个最熟悉的陌生人 —— string.Format.在写C#代码的日子里,与它朝夕相伴,却没有真正去了解它.只知道在字符串比较多时,用它比用加号进行字符串连接效率更高 ...
随机推荐
- python面向对象个人总结
基础概念:面向对象其实就是类与对象的使用. 类是模板,对象是实例.模板创建实例,实例去类里面去执行类的方法.类的例子: class Foo: def Bar(self): ...
- 【软件工程】电梯调度程序需求分析 李亚文&&郭莉莉
2014年3月4日(14:00-16:00) 为了进一步理解电梯工作的原理,我们特地到石家庄铁道大学春晖楼坐了电梯:春晖楼东办共有电梯两部,最高楼层为11层,最低楼层为-1,两电梯可共同使用.结合调查 ...
- openjudge ROADS
726:ROADS 总时间限制: 1000ms 内存限制: 65536kB 描述 N cities named with numbers 1 ... N are connected with one- ...
- Delphi编译的程序,查看控件名称方法
使用SpyLite24这个软件可以查看程序所使用的控件名称
- 【BZOJ3504】危桥(最大流)
题意:见题面 思路:http://www.cnblogs.com/chenyushuo/p/5139556.html 必须交换b1,b2做第二次最大流的原因: 假如一个a1到b2的一个流和b1到a2的 ...
- Android 中的 WebView实现 Html5 标签网页加载
自Android 4.4起,Android中的WebView开始基于Chromium(谷歌浏览器)支持浏览器的一系列功能,webkit解析网页各个节点,这个改变,使得WebView的性能大幅度提升,并 ...
- CSS基本知识和选择器
一.CSS基本知识 内联式css样式,直接写在现有的HTML标签中 内联式css样式表就是把css代码直接写在现有的HTML标签中,如下面代码: <p style="color:red ...
- ZT 第一范式,第二范式,第三范式
第一范式,第二范式,第三范式 Posted on 2012-05-09 16:30 GISerYang 阅读(6472) 评论(0) 编辑 收藏 第一范式 存在非主属性对码的部分依赖关系 R(A,B, ...
- NSPredicate谓词
NSPredicate——谓词(is) 作用:判断条件表达式的求值返回真或假的过程 使用步骤: . 定义NSPredicate对象并指定条件 . 调用谓词的evaluateWithObject方法判断 ...
- Oracle基础知识笔记
1.打开oracle相关服务 2.创建Oracle用户 create user 用户名 identified by 密码;(需要dba角色创建) 3.权限管理 (1)添加权限 grant 权限.角色 ...