简体   繁体   中英

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>
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.

Split the string first. You don't even need regular expressions:

var parts = $('.review-rating').text().split('-');
var date  = $.trim(parts[1])
var from  = $.trim(parts[0]).substring(3);

Here's a demo.

You need to match multiple lines.

var text = $('.review-rating').text();
var matches = text.match(/(.+?)-\s*(.+?)(?:\n|\A)/m);
//matches[1] = oakberrels
//matches[2] = Dec 25, 2011

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM