Fourth Chapter Language Module

Source: Internet
Author: User
Tags script tag mootools javascript array

1. Extension and repair of strings

Language scripts are particularly concerned with strings, and there are three main types of methods:

First Class: Tag-independent implementations : Charat,charcodeat,concat,lastindexof,localecompare,match,replace,slice,split,substr, Substring,tolocalelowercase,tolocaluppercase,tolowercase,touppercase and the method inherited from object. For example, tostring,valueof

The second Category: Tag-related implementations are a pair of tags added to the original string: Anchor,big,blink,blod,fixed,fontcolor,italics,link,small,strike,sub,sup

The third class is a browser method that was later added or not standardized , such as trim,quote,tosource,trimleft,trimright. Trim is standardized and the last four are private implementations of FF.


Let's take a look at the extensions Prototypejs added,

Gsub,sub,scan,truncate,strip,striptags,stripscript,extractscripts,evalscripts,escapehyml,unescapehtml, Parsequery,toarray,succ,times,camelize,capitalize,underscore,dasherize,inspect,unfliterjson,isjson,evaljson, Include,starswith,endswith, Empty,blank,interpolate.

Among them, Gsub,sub,scan is related to the regular, directly take the name of Ruby

truncate is a string intercept and is very useful .

Strip is trim, standardized

Striptags is useful for removing the label pairs of strings .

Stripscript is simply to remove the script tag, exposing Script.text

escapehtml and unescapehtml are very useful for user input and output operation definitions .

Parsequery is basically the operation of the search part of the URL.

Inspect is a double quotation mark at both ends to build the JSON.

Empty and blank are a simple way to determine the blanks.

Prototype.js These frameworks are often copied from other frames, and we know which methods are valuable when we look at the copied functions.

Rightjs string Extensions : Include, Black, camelize, capitalize, dasherize, empty, endswith,evalscripts, extarctscripts, Includes, on, Startswidth, stripscripts, Striptags, Toflaot, ToInt, trim, underscored

MooTools character extensions (prototype extension) test, contains, trim, clean, camelcase, hyphenate, capitalize, Escaperegexp, ToInt, to Float, Hextorgb, Rgbtohex, substitute, stripscripts

Dojo's string extension , rep, pad, substitute, trim, rep is the Repeat method

ext String Extension , capitalize, ellipsis, escape, Escaperegex format HtmlDecode, HtmlEncode Leftpad, parsequerystring, t Rim, Urlappend

Baidu Tangram 's character extensions are: decodehtml, encodehtml, Escapereg, Filterformat, format, FormatColor, Striptags, Tocamelcase, to Halfwidth, Trim, WBR


The following example implements the method:

contains method : Determines whether a string contains another string. conventional thinking, using regular, but each time to use new regexp to construct, too troublesome, poor performance. Instead, use the native string method. such as IndexOf, Lastidexof, search

    function contains (target, it) {        return//indexof change to search, LastIndexOf can    }

In version mootools, we see that it supports more parameters in order to determine whether the classname of an element contains a particular class. As we all know, elements can be added more than one class, separated by a space, the use of Mootoos contains is convenient to detect the inclusion of the relationship.

    function contains (target, str, separator) {        return separator? (separator + target + separator). INDEXOF (separator + str +separator) > -1:target.indexof (str) >-1;    } 

Repeat Method: Repeat a string n times , such as repeat ("Ruby", 2) to get Rubyruby

version 1: Join method with empty array

    function repeat (target, n) {        return (new Array (n + 1)). Join (target);    }

Version 2 ..... 6 ...

version 7, recursion is optimized under the browser, including IE6, one of the best implementations

    function repeat (target, n) {        if (n = = 1)            {return  target        }          var s = repeat (target, Math.floor (N/2));        s + = s        ; if (n% 2) {            + = target        ;        } return s;    }

Bytelen Method: Gets the length of all bytes of a string. This is a back-end way to turn around. At the front end, we want the user to fill in the text, which requires a limit of bytes.

Version 1: Assume that the character Unicode encoding per character is less than or equal to 255,bytelength is a string length. The string is then traversed, and when the Unicode encoding is greater than 255, the ByteLength plus 1

function Bytelen (target) {        var bytelength = target.length,             = 0;          for (; i < target.length; i++) {            if (target.charcodeat (i) > 255) {                BYTELENGTH++;            }        }         return bytelength;    }

The truncate method , which is used to truncate a string, adds three points by default when the limit length is exceeded.

    function truncate (target, length, truncation) {        = length | |         void (0)? ' ... ' : truncation;         return target.length > length? Target.slice (0, length-truncation.length) + truncation:string (target);    }

Camelize method, convert to hump naming style

    function camelize (target) {        if (Target.indexof ('_') < 0 && Target.indexof ('_') < 0) {
    return// advance judgment to improve response efficiency         }        returnfunction  (Match) {            return match.charcodeat (1). toUpperCase ();        })    }

underscored method . Convert to underline style

function underscored (target) {        return target.replace (/([a-z\d]) ([A-z])/g, ' $1_$2 '). Replace (/\-/g, ' _ ') ). toLowerCase ();    }

Dasherize method, converted to a hyphen style , also referred to as CSS variant style (bearing the above method)

    function dasherize (target) {        return underscored (target). Replace (/_/g, '-');    }

Capitalize method, capitalize first letter

    function capitalize (target) {        return target.charat (0). toUpperCase () + target.substring (1). toLowerCase ();    }

Striptags method to remove the HTML tag from the character . But there is a flaw, and if there is a script tag, it will show the scripts that should not be displayed.

    function Striptags (target) {        return String (target | | ""). Replace (/<[^>]+>/g, ');    }

Escapehtml and unescapehtml slightly

Escaperegexp Method : Convert the string security format to the source code of the regular expression

    function Escaperegexp (target) {        return target.replace (/([-.*+?^${} () |[ \]\/\\])/g, ' \\$1 ');    }

Pad Method , in contrast to the trim method, a pad can add a string to one end of a string. It is common to add 0 to the month before the calendar, so it is called Fillzero.

    function pad (target,n) {        varnew Array (n). Join (' 0 ');         var str = zero + target;         var resulet = str.substr (-N);         return resulet;    }

The advanced method, which is also the version used by the mass framework, supports more parameters. Allow padding from left or right. And what content to use to populate.

 function   pad (target, n, filling, right, Radix) { var  num = target.tostring (Radix | | 10); Filling  = Filling | |        "0" ;  while  (num.length < N) { 
   
    if  (!
                right) {num  = filling +
     num;  
    else  
     {num  +=
     filling;         
    return  
     num; }    }
   

Wbr method to add a WBR line to the target string. It is important to note, however, that it does not insert a <wbr> typeface for each string, but rather a specifier insert <wbr> typeface for each word in the report syntax that makes up the text node. If it is AA<SPAN>BB</SPAN>CC, return to A<WBR>A<SPAN>B<WBR>B</SPAN>C<WBR>C<WBR On the Opear browser, the default CSS does not add the WBR style and needs to be added on the CSS, wbr:after{content: "\00200b"} to resolve this issue

    function WBR (target) {        return String (target). Replace (/(?:<[^>]+>) | (?: [0-9a-z] {2,6};) | (. {1}) /gi, ' $&<wbr> '). Replace (/><wbr>/g, ' > ');    }

The format method , in the C language, has a printf method, which we can add later with different types of parameters embedded in the string that will be output. This is a very useful method, because in JavaScript involves a lot of such string concatenation work, if the logic involved, we can use the template, if the lightweight point, we can use this method.

Different names in different frames,prototype.js called Interpolate,base2 called Format,mootools called substitute.

    functionformat (str, object) {varArray = Array.prototype.slice.call (arguments, 1); returnStr.replace (/\\?\#{([^{}]+) \}/GM,function(match, name) {if(Match.charat (0) = = ' \ \ ')                returnMatch.slice (1); varindex =Number (name)if(Index >= 0)                returnArray[index]; if(Object && Object[name]!==void0)                returnObject[name]; return‘‘;    }); }    varA = Format ("Resulet is #{0}, #{1}", 22,33) Console.log (a)//Resulet is    varb = Format ("#{name} is a #{sex} #{am}", {name:"Wangjie", Sex:"Man", am:"111"    }); Console.log (b)//Wangjie is a man 111

It supports two methods, if the placeholder for a string is a non-0 integer such as 0,1,2, requiring two or more arguments to be passed in, otherwise passing in an object with the key name as a placeholder.

The quote method , with double quotes at both ends of the string. Then the internal need to escape is escaped. Used to pick up JSON in the key name or in the modeling system

    //Code.google.com/jquery-json    varescapeable =/["\\\x00-\x1f\x7f-\x9f]/g, Meta= {                        ' \b ': ' \\b ',                        ' \ t ': ' \\t ',                        ' \ n ': ' \\n ',                        ' \f ': ' \\f ',                        ' \ R ': ' \\r ',                        ‘"‘:‘\\"‘,                        ‘\\‘:‘\\\\‘                    }; functionquote (target) {if(Target.match (escapeable)) {return' "' + target.replace (escapeable,function(a) {varc =Meta[a]; if(typeofc = = = ' String ') {                    returnC; }                return' \\u ' + (' 0000 ' + c.charcodeat (0). toString). Slice (-4)            }) + ' "'; }        return"' + target + '" '; }               

Of course, if the browser supports native JSON, we can just use json.stringify , and FF before the JSON invention, Support for String.prototype.quote and String.quote methods, we use quote before we determine whether the browser built-in these methods

The string does not seem to hit the browser compatibility issue, and some words are IE6,IE7 does not support the use of parentheses in the array to take each of its characters, need to use Charat to fetch. IE678 does not support vertical sub-delimiters, so there are hack

var isIe678 =!+ "\v1";

Fix the TRIM function in older versions of IE . This is a very common operation, usually we need to clear the blank on both sides of the form

Version 1, with two regular, real-time speed is amazing, mainly thanks to the browser's internal optimization. BASE2 uses this optimization, causing other browsers to follow suit. So the regular implementation is no more than the string method. A well-known example of string concatenation. The direct addition is faster than the stringbuffer made of array. and StringBuffer technology was highly regarded in the early years.

    function Trim (str) {        return str.replace (/^\s\s*/, "). Replace (/\s\s*$/, ');    }

Version 2

With two candidate operations linked two regular, this loses the chance of browser optimization. Because it looks elegant, many class libraries use it. such as Jquery,mootools

    function Trim (str) {        return str.replace (/^\s+|\s+$/g, ');    }

Version 3

Better version of the improvement

    function Trim (str) {        var str = str.replace (/^\s\s*/, ""),                =/\s/,                =  str.length;      while (Ws.test (Str.charat (--i))        ) return str.slice (0, i + 1);    }

2. Expansion and repair of arrays

Thanks to the prototype.js of the Ruby array method of aggression, let Jser () front-end engineers eye-opener, the original operation of the array is so colorful. The original JavaScript array approach is based on a stack-and-queue approach, like splice () or late. Let's take a look back at the usage.

pop () method, stack operation, delete and return the last element of the array

The push () method, the stack operation, adds one or more elements to the end of the array, and returns the new length.

shift () method, exit operation, delete and return the first element of the array

The unshift () method, the queue operation, adds one or more elements to the beginning of the array, returning the new length

The Slice () method, the slice operation, separates a subarray from the array, functions like a string of substring, slice, and substr three brothers. This method is also commonly used to convert a class array object to a true array

The sort () method, which sorts the array elements, has an optional parameter for the comparison function.

The reverse () method reverses the order of the elements in the array.

The Splice () method, which is used to delete the original array at the same time, the Remove method of the array is written based on it.

The concat () method is used to combine the original array with the parameters into a new array, and if the argument is an array, it puts the elements of its first dimension into the new array. So we can use it to implement the flattening and cloning operations of arrays.

Join () method to put all the elements of an array into a string. element is delimited by the specified delimiter. You can imagine the inverse of the split as a string.

In ECMA262V5, the standard browser has already implemented several methods in the household processing. From then on, we can safely use the foreach () method without worrying about them being discarded.

indexOf () method, locate the operation. Ibid., not from post-traversal. An index operation can be said to be a replica of a string with a method of the same name, and a non-negative operation exists. Returns-1 if not present.

The ForEach () method. Iterative operations. The elements of the array are sequentially passed into a function, and the prototype.js corresponding names are each.

map () method to collect the operation. The elements of the array are sequentially passed into a function, and then the return values of the arrays are made into a new array. The prototype.js corresponds to the name collect.

Fliter () method. The filter operation executes the elements of the array into a function in turn, and then returns the element with the return value of true into the new array. In Prototype.js it has three names, select, Filter, FindAll

The Some () method, as long as there is an element in the array that satisfies the condition (put in the function returns True). Then it returns true.prototype.js corresponding to the name of any

The every () method only returns True if the element of the array satisfies the condition (putting in the given function returns True). Prototype.js the corresponding name is any

reduce () method, domestication operation. The elements in the array are grouped into a simple numeric value. Prototype.js corresponds to the name inject

reduceright () method: A domestication operation that converts an element in an array to a simple numeric value. Ibid., but is traversed from behind.

Since many extensions are also based on these new standard methods, we first give the IE678 compatibility scheme, all of which fix them on the array prototype.

(not to be continued )

The following updates are:

3. Expansion and repair of numerical values

4. Extension and repair of functions

5. Extension and repair of dates

Fourth Chapter Language Module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.