[翻译]High Performance JavaScript(018)
String Trimming 字符串修剪
Removing leading and trailing whitespace from a string is a simple but common task. Although ECMAScript 5 adds a native string trim method (and you should therefore start to see this method in upcoming browsers), JavaScript has not historically included it. For the current browser crop, it's still necessary to implement a trim method yourself or rely on a library that includes it.
去除字符串首尾的空格是一个简单而常见的任务。虽然ECMAScript 5添加了原生字符串修剪函数(你应该可以在即将出现的浏览器中看到它们),到目前为止JavaScript还没有包含它。对当前的浏览器而言,有必要自己实现一个修剪函数,或者依靠一个包含此功能的库。
Trimming strings is not a common performance bottleneck, but it serves as a decent case study for regex optimization since there are a variety of ways to implement it.
修剪字符串不是一个常见的性能瓶颈,但作为学习正则表达式优化的例子有多种实现方法。
Trimming with Regular Expressions 用正则表达式修剪
Regular expressions allow you to implement a trim method with very little code, which is important for JavaScript libraries that focus on file size. Probably the best all-around solution is to use two substitutions—one to remove leading whitespace and another to remove trailing whitespace. This keeps things simple and fast, especially with long strings.
正则表达式允许你用很少的代码实现一个修剪函数,这对JavaScript关心文件大小的库来说十分重要。可能最好的全面解决方案是使用两个子表达式:一个用于去除头部空格,另一个用于去除尾部空格。这样处理简单而迅速,特别是处理长字符串时。
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+/, "").replace(/\s+$/, "");
}
}
// test the new method...
// tab (\t) and line feed (\n) characters are
// included in the leading whitespace.
var str = " \t\n test string ".trim();
alert(str == "tes
相关文档:
页面提交数据一般有两种方法:get,post。post就是所谓的form提交,使用视图;get是通过url提交。
Get方法一般用后台代码(如asp,asp.net)获得参数,代码很简单:Request.QueryString["id"];即可获取。
有些时候需要直接在前台获取url参数,要用到javascript,js没有直接获取url参数的方法,那么,我们如何通过js ......
var
xmlDoc
=
null
;
function
parseXML
(
xmlUrl
)
{
try
{
//IE
xmlDoc
=
new
ActiveXObject
(
"Microsoft.XMLDOM"
);
xmlDoc
.
async
=
false
;
xmlDoc
......
常规的方法是将年月日取出,然后分别判断范围,然后就判断闰年2月的天数
可以通过new Date(string)的构造,比较年月日字符是否发生变化判断。
function CheckDate(text) {
if (!text) return false;
text = text.replace(/[\/-]0?/g, "/");
if (!text.match(/^\d{4}\/\d{1,2}\/\d{1,2}$/)) return true;
......
Repaints and Reflows 重绘和重排版
Once the browser has downloaded all the components of a page—HTML markup, JavaScript, CSS, images—it parses through the files and creates two internal data structures:
当浏览器下载完所有页面HTML标记,JavaScri ......
Recursion Patterns 递归模式
When you run into a call stack size limit, your first step should be to identify any instances of recursion in the code. To that end, there are two recursive patterns to be aware of. The first is the straightforward recursive pattern represented ......