Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex and trim everything after "dash"

For the html below, I am trying to put a variable to just "oakbarrels" and a variable to just "Dec 25, 2011". I have already been able to get the "Dec 25, 2011" with regex but I cannot figure out how to get the rest. Basically I want to remove "By " and everything after the first " -":

<p class="review-rating">
         By oakbarrels
         - Dec 25, 2011
         -
         Something.com
</p>
<script>
    var thedate =  $('.review-rating').text().match(/\-\s([^\n]+)/)[1].trim();
    var from = ???
</script>
like image 717
ToddN Avatar asked Aug 03 '26 05:08

ToddN


1 Answers

var matches = $('.review-rating').text().match(/\s*By\s+(\w+)\s*-\s*([\w, ]+)/);

jsFiddle.

matches[1] will contain 'oakbarrels' and matches[2] will contain 'Dec 25, 2011', as per your example.

I also changed your html() to text(). It doesn't appear the HTML is relevant to matching the text.

like image 75
alex Avatar answered Aug 04 '26 21:08

alex