0

I want to extract the date and the username from string using .split() in this particular string:

var str ='<a href="/user/xxspmxx/profile">XxSPMxX</a> on 08/30/2012';

I want XxSPMxX in one variable and 08/30/2012 in the other.

Zoltan Toth
47.8k12 gold badges132 silver badges138 bronze badges
asked Sep 4, 2012 at 20:47
1
  • It wasn't before Zoltan edited the question. Commented Sep 4, 2012 at 20:53

3 Answers 3

3

Using just split:

var x = str.split('</a> on ');
var name = x[0].split('>')[1];
var date = x[1];

Demo: http://jsfiddle.net/Guffa/YUaAT/

answered Sep 4, 2012 at 20:54
Sign up to request clarification or add additional context in comments.

Comments

2

I don't think split is the right tool for this job. Try this regex:

var str ='<a href="/user/xxspmxx/profile">XxSPMxX</a> on 08/30/2012',
 name = str.match(/[^><]+(?=<)/)[0],
 date = str.match(/\d{2}\/\d{2}\/\d{4}/)[0];

Here's the fiddle: http://jsfiddle.net/5ve7Y/

answered Sep 4, 2012 at 20:52

Comments

0

Another way would be to match using a regular expression, build up a small array to get the parts of the anchor, and then use substring to grab the date.

var str = '<a href="/user/xxspmxx/profile">XxSPMxX</a> on 08/30/2012';
var matches = [];
str.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function () {
 matches.push(Array.prototype.slice.call(arguments, 1, 4))
});
var anchorText = matches[0][2];
var theDate = str.substring(str.length - 10, str.length);
console.log(anchorText, theDate);

working example here: http://jsfiddle.net/dkA6D/

answered Sep 4, 2012 at 21:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.