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
rajat
3,56317 gold badges60 silver badges93 bronze badges
-
It wasn't before Zoltan edited the question.Diodeus - James MacFarlane– Diodeus - James MacFarlane2012年09月04日 20:53:07 +00:00Commented Sep 4, 2012 at 20:53
3 Answers 3
Using just split:
var x = str.split('</a> on ');
var name = x[0].split('>')[1];
var date = x[1];
answered Sep 4, 2012 at 20:54
Guffa
703k112 gold badges760 silver badges1k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Joseph Silber
221k59 gold badges369 silver badges293 bronze badges
Comments
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
Tim B James
20.4k4 gold badges77 silver badges108 bronze badges
Comments
lang-js