Javascript advanced Article 1 Regular Expressions, cookie management, userData

Source: Internet
Author: User

First of all, what is a regular expression? In fact, the introduction of the concept often does not help us understand what it is, so I will briefly describe it, it is actually a string that records string rules. After reading this part, we can understand what it is.

Basic Syntax: the regular expression is the "/expression/" + symbol indicating the search range. For example, the keyword "function" is/function/gi, where g indicates global, global search, I indicates ignor, and case-insensitive.

In js, we use the RegExp class.

There are many symbols in this class to indicate different indexing methods. First, let's put a column in this table:

Metacharacters Description Quantifiers Description Negative characters Description
. Match any character except the newline character (\ n) * Number of occurrences: [0, + ∞) \ W Letters, numbers, underscores (_), other than Chinese Characters
^ Start of matching string + Number of occurrences: [1, + ∞) \ S Characters other than white space characters
$ End of matching string ? Number of occurrences: [0, 1] \ D Characters other than numbers
\ B Match word boundary {N} Number of occurrences: n \ B Match non-word boundary
\ D Matching number {N ,} Number of occurrences: [n, + ∞) [^] Any character other than the character string after the ^ character in the character class
\ S Match any blank space character {N, m} Number of occurrences: [n, m] [-] Match the characters/numbers in the string from-prefix to-suffix
\ W Match letters, numbers, underscores or Chinese Characters

In addition to the above symbols, there are three concepts: group, reverse reference, and candidate.
Grouping: Enclose strings with (), so that strings can be combined according to certain rules. At the same time, parentheses can also be nested. For example, the regular expression is used to express the Date Format: var dateReg =/^ (\ d })(-) (\ d {1, 2} (-) (\ d {1, 2}) $). Of course, this method also has some vulnerabilities. Here, it only indicates the format problem.
In addition to square brackets, for example, if you only want to match one of the letters x y z d w, write [xyzdw]. If the matching is continuous, for example, a 0-4 number can be [0-4], but it only represents one character.
If you want to write multiple, such as matching the ac or bd, use the "|" symbol to write (ac | bd ).
For example, if we want to match a string that only contains abc, we can write: abdReg =/^ [abc] + $/; below is a complete example.Copy codeThe Code is as follows: <Head>
<Title> regular express </title>
<Script type = "text/javascript">
Var str = "agedaga ";
Var str2 = "acbaaaccbac ";
Var abcReg =/^ [abc] + $/g;
Var test1 = false;
Var test2 = false;
If (abcReg. test (str ))
Test1 = true;
If (abcReg. test (str2 ))
Test2 = true;
Document. write ("result of string" + str + "is:" + test1 + "<br> resulet of string" + str2 + "is:" + test2 );
</Script>
</Head>
<Body>
<Body>
</Html>

Reverse reference: an application of a regular expression based on a group. First, you need to know the group number. The group numbers are marked by left brackets in the order from left to right, and are accumulated from 1. You can use either the $ group number or the \ group number.
The second method is suitable for referencing a group in an expression. "\" is an escape character, which is used to match a reserved character, just as it usually means.
For example, we want to match a string that starts with abc and ends with abc. There is no limit in the string: Reg =/^ (abc) [a-z] * \ 1 $ /; you can put this sentence in the example just now and try again. I tested it without errors.
Several common matching Regular Expressions:
1. matching Date: reg =/^ \ d {4}-(0 [13578] | (10 | 12 )) -(0 [1-9] | [1-2] \ d | 3 [01]) | (02-(0 [1-9]) | [1-2] \ d) | (0 [469] | 11)-(0 [1-9] | [1-2] \ d | 30 ))) $/g;
2. matching time: reg =/^ ([0-1] \ d | [2] [0-3] ([0-5] \ d )) {2} $/g;
3. matched Email: reg =/^ ([a-zA-Z] ([0-9a-zA-Z] | (_) * @ ([0-9a-zA-Z] | (_) + \.) + [a-zA-Z] {2, 9}) $/g;
4. Match Chinese characters: reg =/^ [\ u4e00-\ u9fa5] + $/g;
Javascript cookies
Cookie is what everyone believes, so I will not die.
The statement for using js to operate a cookie is as follows: document. cookie = name + "=" value + "; expires =" + date. toGMTString ();
Next, we will use cookies to record the user name and password for login.Copy codeThe Code is as follows: <Head>
<Title> cookie test </title>
<Script type = "text/javascript">
Function setCookie (cookieName, cookieValue, expires ){
Document. cookie = cookieName + "=" + escape (cookieValue) + "; expires =" + expires. toGMTString ();
}
Function conf (){
Var form = document. form;
Var uname = form. username. value;
Var upasw = form. pasw. value;
Var expires = new Date ();
Expires. setTime (expires. getTime () + (7*24*60*60*1000 ));
SetCookie ("username", uname, expires );
Alert ("cookie seted ");
}
</Script>
</Head>
<Body>
<Form name = "form" method = "post" action = "#">
<Table width = "300" align = "center" border = "1">
<Tr>
<Td align = "center"> user name: <input type = "text" name = "username"> </td>
</Tr>
<Tr>
<Td align = "center"> password: <input type = "password" name = "pasw"> </td>
</Tr>
<Tr>
<Td align = "center"> <input type = "button" name = "confirm" value = "confirm" onclick = "conf ()"> </td>
</Tr>
</Table>
</Form>
<Body>
</Html>

It indicates that escape is simple encryption, and expires is the lifetime. It is generally set to one week and will be automatically deleted one week later.
Of course, if you only write a cookie but do not read it, you should read the content of the cookie file.
So we add two read functions to the script:Copy codeThe Code is as follows: <script type = "text/javascript">
Function getCookie (cookieObj, cookieName ){
Var startIndex = cookieObj. indexOf (cookieName );
If (startIndex =-1) return null; // no cookie
StartIndex + = cookieName. length + 1; // alert (startIndex );
Var endIndex = cookieObj. indexOf (";", startIndex );
If (endIndex =-1)
EndIndex = cookieObj. length;
Return unescape (cookieObj. substring (startIndex, endIndex ));
}
Function getInfo (){
Var form = document. form;
Var cookie = document. cookie;
Var userName = getCookie (cookie, "username"); // get cookie by cookiename
If (userName & userName. length> 0)
Form. username. value = userName;
Else
Alert ("no cookie info! ");
}
</Script>

In addition, we need to add an onload event to the body Tag:
<Body onload = "getInfo ()">
Therefore, this code runs correctly in IE and FF, and uses cookies in chrome .. I really don't understand ~ Do you know what the hero is ~ Orz
Modifying the cookie validity period is the same as modifying the cookie content. However, you can find the expires field and modify it. If you want to delete the cookie, set its validity period to yesterday.
UserData
Different from cookie, userData does not have a validity period and can store more data (640KB cookie: 4KB). Therefore, if the page input volume is large, userData can be used to store data.
Save the data to userData. It consists of two parts: Name the content and store it in userData.
Before learning, you should note that this is developed by Microsoft, so it is only applicable to IE. After testing, FF and chrome indicate that this function is not compatible.
Here, a graph is written about the stored calendar table:

OK. Let's take a look at userData.
First, add a style in front of the script and save it to userData by setting parameters:Copy codeThe Code is as follows: <Head>
<Title> cookie test </title>
<Style>
. UserData
{
Behavior: url (# default # userdata );
}
</Style>
<Script type = "text/javascript">
Function conf (){
Var formObj = document. form;
Var contentObj = document. content;
ContentObj. setAttribute ("contentText", contentObj. value );
ContentObj. save ("contentData"); // save it in the contentData Storage Area
}
</Script>
</Head>
<Body>
<Form name = "form" method = "post" action = "#">
<Table width = "400" align = "center" border = "1">
<Tr>
<Td> title: </td>
<Td> <input type = "text" name = "title" size = "50"> </td>
</Tr>
<Tr>
<Td> content: </td>
<Td> <textarea name = "content" class = "userData" cols = "45" rows = "10"> </textarea> </td>
</Tr>
<Tr align = "center">
<Td colspan = "2" align = "center"> <input type = "button" name = "Save" value = "confirm" onclick = "conf () "> </td>
</Tr>
</Table>
</Form>
<Body>
</Html>

The retrieved function is the opposite of the stored function. It is actually easy to understand:
Add a function:Copy codeThe Code is as follows: function getContent (){
Var formObj = document. form;
Var contentObj = formObj. content;
ContentObj. load ("contentData ");
ContentObj. value = contentObj. getAttribute ("contentText ");
}

Complete program after modification:Copy codeThe Code is as follows: <Head>
<Title> cookie test </title>
<Style>
. UserData {behavior: url (# default # userData );}
</Style>
<Script type = "text/javascript">
Function saveContent (){
Var formObj = document. form;
Var contentObj = formObj. content;
ContentObj. setAttribute ("contentText", contentObj. value );
ContentObj. save ("contentData"); // save it in the contentData Storage Area
Alert ("saved ");
}
Function getContent (){
Var formObj = document. form;
Var contentObj = formObj. content;
ContentObj. load ("contentData ");
ContentObj. value = contentObj. getAttribute ("contentText ");
}
</Script>
</Head>
<Body onload = "getContent ()">
<Form name = "form" method = "post" action = "#">
<Table width = "400" align = "center" border = "1">
<Tr>
<Td> title: </td>
<Td> <input type = "text" name = "title" size = "50"> </td>
</Tr>
<Tr>
<Td> content: </td>
<Td> <textarea name = "content" class = "userData" cols = "45" rows = "10"> </textarea> </td>
</Tr>
<Tr align = "center">
<Td colspan = "2">
<Input type = "button" name = "Save" value = "confirm" onclick = "saveContent ()">
</Td>
</Tr>
</Table>
</Form>
<Body>
</Html>

The next step is compatibility: (the following sections are all copied, because I don't know the source .)
LocalStorage: compared with other solutions, localStorage has its own advantages: large capacity, easy-to-use, powerful, and native support. Its disadvantages are poor compatibility (chrome, safari, firefox, IE 9, IE8 supports localStorage, which is not supported by IE8 or earlier versions. The security is also poor (therefore, do not use localStorage to store sensitive information ).

Very easy-to-understand interface:

LocalStorage. getItem (key): Get the value of the local storage of the specified key
LocalStorage. setItem (key, value): store the value to the key field
LocalStorage. removeItem (key): deletes the value of the local storage of the specified key.

Note that the values stored in localStorage are strings. When processing complex data, such as json data, you need to convert the JSON string to a truly available json format by using the json class, the second practical tutorial on localStorage will focus on demonstration of related functions. LocalStorage also provides a storage event that is triggered after the stored value changes.
Currently, browsers all provide excellent debugging functions for developers. The following are the debugging tools for Chrome and Firefox respectively.

After a long time of decommission, I finally wrote advanced 1 in an energetic spirit. In the future, I will not be able to fall so far .. It is still necessary to practice with closed customs ~.

Related Article

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.