开发者

Javascript regexp replace, multiline

开发者 https://www.devze.com 2023-04-13 00:46 出处:网络
I have some text content (read in from the HTML using jQuery) that looks like either of these examples:

I have some text content (read in from the HTML using jQuery) that looks like either of these examples:

<span>39.98</span><br />USD

or across multiple lines with an additional price, like:

<del>47.14</del>

    <span>39.98</span><br />USD

The numbers could be formatted like

  • 1,234.99
  • 1239,99
  • 1 239,99

etc (i.e. not just a normal decimal number). What I want to do is get just whatever value is inside the <span></span>.

This is what I've come up with so far, but I'm having problems with the multiline approach, and also the fact that there's potentially two numbers and I want to ignore the first one. I've tried variations of using ^ and $, and the "m" multiline modifier, but no luck.

var strRegex = new RegExp(".*<span>(.*?)</span>.*", "g");

var strPrice = strContent.replace(strRegex, '$1');

I could use jQuery here if there's a way to target the span tag inside a string开发者_如何学C (i.e. it's not the DOM we're dealing with at this point).


You could remove all line breaks from the string first and then run your regex:

strContent = strContent.replace(/(\r\n|\n|\r)/gm,"");
var strRegex = new RegExp(".*<span>(.*?)</span>.*", "g");
var strPrice = strContent.replace(strRegex, '$1');


This is pretty easy with jQuery. Simply wrap your HTML string inside a div and use jQuery as usual:

var myHTML = "<span>Span 1 HTML</span><span>Span 2 HTML</span><br />USD";
var $myHTML = $("<div>" + myHTML + "</div>");

$myHTML.find("span").each(function() {
   alert($(this).html()); 
});

Here's a working fiddle.


try using

"[\s\S]*<span>(.*?)</span>[\s\S]*"

instead of

".*<span>(.*?)</span>.*"

EDIT: since you're using a string to define your regex don't forget to esacpe your backslashes, so

[\s\S] 

would be

[\\s\\S]


You want this?

var str = "<span>39.98</span><br />USD\n<del>47.14</del>\n\n<span>40.00</span><br />USD";

var regex = /<span>([^<]*?)<\/span>/g;

var matches = str.match(regex);

for (var i = 0; i < matches.length; i++)
{
    document.write(matches[i]);
    document.write("<br>");
}

Test here: http://jsfiddle.net/9LQGK/

The matches array will contain the matches. But it isn't really clear what you want. What does there's potentially two numbers and I want to ignore the first one means?

0

精彩评论

暂无评论...
验证码 换一张
取 消