Javascript: Declare variables from RegEx, write to cookie
This question has two parts.
First, I need to isolate two strings of text inside a span with the class "test01". Here is what the span looks like:
<span class="test01">
<table width="100%" cellspacing="0" cellpadding="0">
<tbody><tr><td>
<div id="ctl00_ctl07_pnTopBar">
<a href="/Member/MyHome.aspx">My Account</a> <a href="/faqs.html">Help</a> <a href="/Cart.aspx">Cart</a> <a href="/contact.html">Contact Us</a> <a href="/disclaimer.html">Disclaimer</a>
</div>
</td>
</tr><tr>
<td align="right">
email@address.com (UserId: 123456)
<a href="javascript:__doPostBack('ctl00$ctl07$EasyLoginView1$lv$EasyLoginStatus$ctl00','')" id="ctl00_ctl07_EasyLoginView1_lv_EasyLoginStatus">Logout</a>
</td></tr>
</tbody></table>
&l开发者_如何学Got;/span>
How would I go about isolating the email address, and the ID number (which is not always six digits long), and declare them as variables 'email' and 'uid' ?
Part two- I am also wondering how one would use javascript to write each of these variables to respective cookies.
This is a jQuery solution.
When creating this function, I was assuming the following:
- The needed data is always in the last TD (can be easily modified though, easiest would be to add an ID to the TD).
- The userID stuff is always inside parentheses.
- The userID only consists of numbers.
It basically gets the text of the TD, splits it based on the parentheses, the first one will be the email, the numbers in the second one will be the userID.
$(document).ready(function () {
var cucc=$('.test01 td:last').text();
var temb=cucc.split(/\(|\)/);
var email=$.trim(temb[0]);
var uid=temb[1].replace(/[^0-9]/g, '');
});
Working JSFiddle
To set cookies with jQuery, please see this article about the Cookie Plugin.
This can be done in two teps. First search for:
<span class="test01">(.*?)</span>
Then you iterate thru the matches with:
([a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@([a-z0-9_-]+\.)+[a-z]{2,4}) \(UserId: ([0-9]+)
The first backreference will contain the e-mail address and the third one will have the id.
I used all legal character in an e-mail address, in real life it's extremely rare to use smeting like ?
in an address.
精彩评论