InterviewSolution
| 1. |
Search for a string in a string with JavaScript |
|
Answer» Cookies has a plain text RECORD of fields: Expires, Domain, Path, Secure, etc. They are generally used to track preferences, commissions, etc. It stores information on your computer in the form of plain text. Cookies are saved in name-value pairs. It gets deleted when the web browser is closed. Let us see how we can create a cookie in JavaScript: The document.cookie property is used in JavaScript to create cookies. With the same property, you can also read and delete cookies. Create a cookie: document.cookie = "username=Knowledge Hut";Add an EXPIRY date to the cookie created above: document.cookie = "username= Knowledge Hut; expires=Thu, 12 Dec 2018 12:00:00 UTC";To read a cookie in JavaScript: var a = document.cookie;The above displays the cookies in name-value form i.e.: cookie1=value; cookie2=value;To delete a cookie, you need to just set the cookie to the past date (expire). The date is included USING the expires parameter: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";Let us see an example that CREATES a cookie: <html> <head> <script> <!-- function displayCookie() { if( document.one.dept.value == "" ){ alert("Enter some value!"); return; } val = escape(document.one.dept.value) + ";"; document.cookie="name=" + val; document.write ("Setting Cookie <br> " + "name=" + val ); } //--> </script> </head> <body> <form name="one" action=""> Enter Department: <input type="text" name="dept"/> <input type="button" value="Input Cookie" onclick="displayCookie();"/> </form> </body> </html>The output displays an input box, wherein we add a value to set as cookie: On clicking “Input Cookie” above, you can see that we have set the cookie successfully: |
|