[·Òë]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
Ïà¹ØÎĵµ£º
±¾ÎÄÖ÷ÒªÊdzöÓÚÓÐÅóÓÑʹÓÃÎÒÔÀ´Ð´µÄautocompleteµÄJS¿Ø¼þ¡£µ±Êý¾ÝÁ¿´óµÄʱºò£¬»á³öÏÖЧÂʼ«ÆäÂýµÄÇé¿ö£¬ÎÒÔÚÕâ¶Îʱ¼ä×ö³öµÄһЩ²âÊÔÒ²¼°Ò»Ð©¾Ñ飬Óë´ó¼Ò·ÖÏí£¬Èç¹ûÓдíµÄµØ·½£¬»¹ÇëÖ¸³ö¡£
¾¹ý²âÊÔ£¬ÎÒÃǻᷢÏÖÈçϵÄÇé¿ö»òÕß˵µÄ½áÂÛ£¬Èç¹ûÄúµÄ²âÊÔ½á¹ûÓëÎҵIJ»·û£¬Çë˵Ã÷ÔÒò£¬ÒÔ±ãÏ໥ѧϰ¡£
1£©µ±Ò»¸ö½Ï´óµÄHTML×Ö· ......
ÃæÏò¶ÔÏóµÄÓïÑÔ¶àÊý¶¼Ö§³Ö¼Ì³Ð£¬¼Ì³Ð×îÖØÒªµÄÓŵã¾ÍÊÇ´úÂ븴Ó㬴Ӷø¹¹½¨´óÐÍÈí¼þϵͳ¡£Èç¹ûÒ»¸öÀàÄܹ»ÖØÓÃÁíÒ»¸öÀàµÄÊôÐԺͻò·½·¨£¬¾Í³Æ֮Ϊ¼Ì³Ð¡£
´ÓÕâ¸ö½Ç¶ÈÀ´¿´¿´jsµÄ¼Ì³Ð·½Ê½¡£jsÖм̳з½Ê½ÓëдÀ෽ʽϢϢÏà¹Ø¡£²»Í¬µÄдÀ෽ʽÔì³É²»Í¬µÄ¼Ì³Ð·½Ê½¡£¸÷ÖÖÁ÷ÐÐjs¿â¼Ì³Ð·½Ê½Ò²¸÷²»Ïàͬ¡£´Ó×î¼òµ¥µÄ
¸´ÓÿªÊ¼¡£
1¡¢¹¹Ôìº ......
[ת×Ô]http://article.yeeyan.org/view/mouse4x/16540
JSON±»¹«ÈÏΪä¯ÀÀÆ÷ÖÐXMLµÄºó¼ÌÕߣ¬ËüµÄÄ¿±ê½ö½öÊdzÉΪһÖÖ¼òµ¥¡¢ÓÅÑŵÄÊý¾Ý¸ñʽ£¬ÒÔ·½±ãä¯ÀÀÆ÷ºÍ·þÎñÆ÷Ö®¼äµÄÊý¾Ý½»»»¡£ÔÚÍê³ÉÕâÒ»¼òµ¥ÈÎÎñµÄ¹ý³ÌÖУ¬Ëü½«ÒýÁìÏÂÒ»´úÍòάÍø¡£
¶ÔÏó¼ò½é
¿´,Õâ¾ÍÊÇÒ»¸ö¶ÔÏó:
var myFirstObject ={};
¾¡¹Ü¿´ÆðÀ´Í¦¼òµ¥£¬È»¶øÄÇЩ» ......
Regular Expression Optimization ÕýÔò±í´ïʽÓÅ»¯
Incautiously crafted regexes can be a major performance bottleneck (the upcoming section, "Runaway Backtracking" on page 91, contains several examples showing how severe this can be), but there is a lot you can do to improve re ......