JavaScript advanced 1 Regular expressions, cookie management, Userdata_ basics

Source: Internet
Author: User
Tags setcookie
First of all, what's the regular expression? In fact, the introduction of concepts often does not help us understand what it is, so I would like to briefly describe the regular expression, in fact, is a string of records string rules, and so we read this part, we can understand what it is.

Basic syntax: Regular expressions are "/expression/" + symbols that represent search scopes. For example, we are looking for function this keyword, is/function/gi, where G represents global, is global search, I means ignor, is ignoring case.

In JS, we implement the RegExp class.

There are lots and lots of symbols in this class to represent different indexing methods, so I'll make a column of this table:
Metacharacters Description Quantifiers Description Anti-literal characters Description
. Matches any character except the newline symbol (\ n) * Number of occurrences: [0,+∞) \w Letters, numbers, underscores, characters other than Chinese characters
^ Match the start of a string + Number of occurrences: [1,+∞] \s Characters other than white-space characters
$ End of Match string ? Number of occurrences: [0,1] \d A character other than a number
\b Match word boundaries N Number of occurrences: n \b Match a non-word boundary
\d Matching numbers {N,} Number of occurrences: [n,+∞] [^] In the character class, any character other than the string that follows the ^ number
\s Match any white space character {N,m} Number of occurrences: [N,m] [-] Match characters/digits in strings from-pre-character to-after characters
\w Match letters, numbers, underscores, or Chinese characters

In addition to the above symbols, there are three concepts: one is a grouping, one is a reverse reference, and finally a candidate.
Grouping: Refers to the use of () to enclose strings, so that strings can be grouped according to a certain pattern. At the same time, parentheses can also be nested, such as using regular expressions to express the format of the date: Var datereg=/^ (\d{1,4}) (\d{1,2} (-) (\d{1,2}) $), of course, this method also has a certain loophole, here just to express the format problem.
In addition to these, there are parentheses, for example, if you only want to match one of the few letters X y z D, write [XYZDW], if the match is continuous, such as 0-4 of the number that is [0-4], but this is only one character.
If you want to write multiple, such as matching AC or BD, then use the "|" symbols, writing (AC|BD).
For example, if we want to match a string that contains only ABC, then we can write: abdreg=/^[abc]+$/; The following is a complete example.
Copy Code code as follows:

<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+" are: "+test1+" <br> Resulet of string "+str2+" is: "+test2);
</script>
<body >
<body>

Reverse reference: Is the application of regular expressions based on grouping. First you need to know the grouping number: The left parenthesis is the sign of the grouping from left to right, starting at 1. There are two ways to use it: $ group number, or group number.
The second applies when grouping is referenced in an expression, where "\" is an escape symbol, which, as usual, is used when a reserved character needs to be matched.
For example, we want to match an ABC start, ABC end, the middle of an open-ended string: reg=/^ (ABC) [a-z]*\1$/; You can put this sentence in the example just now to try, I tested there is no error.
Several common matching regular types:
1. Date of match: 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. Match time: reg=/^ ([0-1]\d|[ 2][0-3] (:([0-5]\d)) {2}$/g;
3. Matching mailbox: reg=/^ ([A-za-z] ([0-9a-za-z]| ( _)) *@ ([0-9a-za-z]| (_)) +\.) +[a-za-z]{2,9}) $/g;
4. Matching Chinese characters: reg=/^[\u4e00-\u9fa5]+$/g;
JavaScript Operation Cookies
Cookie is what I believe everyone is, so I don't Dengbal the definition of BA.
Use JS to operate the cookie statement as follows: document.cookie=name+ "=" value+ "; expires=" +date.togmtstring ();
Next, we use cookies to record user names and passwords logged in by users.
Copy Code code as follows:

<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>
<body >
<form name= "form" method= "POST" action= "#" >
<table width= "align=" "Center" border= "1" >
<tr>
&LT;TD align= "center" >user name:<input type= "text" name= "username" ></td>
</tr>
<tr>
&LT;TD align= "center" >password: <input type= "password" name= "PASW" ></td>
</tr>
<tr>
&LT;TD align= "center" ><input type= "button" name= "Confirm" value= "confirm" onclick= "conf ()" ></td>
</tr>
</table>
</form>
<body>

Explain that escape is a simple encryption, expires is the survival period, generally set to a week, after a week automatically deleted.
Of course, if you just write cookies but do not read the white blind, so learn to read the contents of the cookie file.
So we added two functions to read in the script:
Copy Code code 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 cookies by CookieName
if (username&&username.length>0)
Form.username.value=username;
Else
Alert ("No cookie info!");
}
</script>

In addition to the body tag added a onload event:
<body onload= "GetInfo ()" >
So the code executes correctly in IE and FF, and there is no cookie in chrome. I really do not understand the ~ have to know why the Warrior ~ ~ Ask Enlighten Orz
Modifying the cookie's expiration date is the same as modifying the cookie content, but finding the Expires field content and then modifying it, if you want to delete the cookie, set its expiration date to be OK yesterday.
UserData
Unlike cookies, UserData can have no expiration date and can store more data (640KB cookie:4kb), so you can use UserData to store the data if the page input is large.
Save data to UserData: It's mainly two parts: give the content a name and save it to the UserData.
Before learning to note that this is developed by Microsoft, so only for IE, tested, FF and Chrome is not compatible with this feature.
Here's a picture of a stored almanac:

OK, take a look at UserData.
First, add a style before the script, and then save it to UserData by setting the parameters:
Copy Code code as follows:

<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 in contentdata storage area
}
</script>
<body >
<form name= "form" method= "POST" action= "#" >
<table width= "align=" "Center" border= "1" >
<tr>
<td>title:</td>
<td><input type= "text" name= "title" Size= "></td>"
</tr>
<tr>
<td>content:</td>
<td><textarea name= "Content" class= "UserData" cols= "a" rows= "ten" ></textarea></td>
</tr>
&LT;TR align= "center" >
&LT;TD colspan= "2" align= "center" ><input type= "button" Name= "Save" value= "Confirm" onclick= "conf ()" &GT;&LT;/TD >
</tr>
</table>
</form>
<body>

The process of getting a function is the opposite of a store, and it is actually very well understood:
Add a function:
Copy Code code as follows:

function GetContent () {
var formobj=document.form;
var contentobj=formobj.content;
Contentobj.load ("Contentdata");
Contentobj.value=contentobj.getattribute ("ContentText");
}

The complete program after the change:
Copy Code code as follows:

<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 in contentdata storage area
Alert ("Saved");
}
function GetContent () {
var formobj=document.form;
var contentobj=formobj.content;
Contentobj.load ("Contentdata");
Contentobj.value=contentobj.getattribute ("ContentText");
}
</script>
<body onload= "getcontent ()" >
<form name= "form" method= "POST" action= "#" >
<table width= "align=" "Center" border= "1" >
<tr>
<td>title:</td>
<td><input type= "text" name= "title" Size= "></td>"
</tr>
<tr>
<td>content:</td>
<td><textarea name= "Content" class= "UserData" cols= "a" rows= "ten" ></textarea></td>
</tr>
&LT;TR align= "center" >
&LT;TD colspan= "2" >
<input type= "button" Name= "Save" value= "Confirm" onclick= "savecontent ()" >
</td>
</tr>
</table>
</form>
<body>

OK next to say a compatibility is OK: (The following paragraph is copied, because the reprint too much I do not know the source of origin.) )
Localstorage: Compared with other schemes, Localstorage has its own advantages: large capacity, ease of use, strong, native support; The disadvantage is that compatibility is worse (Chrome, Safari, Firefox,ie 9,ie8 all support Localstorage, This is mainly IE8 the following version is not supported, and security is also poor (so do not use Localstorage to save sensitive information).

Very easy to understand interface:

Localstorage.getitem (Key): Gets the value of the specified key local store
Localstorage.setitem (key,value): Store value in key field
Localstorage.removeitem (key): Deletes the value locally stored for the specified key

Note that the values stored by Localstorage are string types, and when dealing with complex data, such as JSON data, you need to use the JSON class to convert the JSON string to a truly available JSON format, localstorage the second hands-on tutorial will focus on the relevant features. Localstorage also provides a storage event that fires after the stored value changes.
Browsers now have good developer debugging capabilities, and the following are the Chrome and Firefox debugging tools to view

Scrapped for a long time, finally vim 1 write well, after no longer so degenerate ah. Retreat cultivation is still necessary ~.

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.