[英]Javascript regexp replace, multiline
I have some text content (read in from the HTML using jQuery) that looks like either of these examples: 我有一些文本内容(使用jQuery从HTML中读取),看起来像这些示例之一:
<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 数字可以格式化为
etc (ie not just a normal decimal number). 等(即不仅仅是正常的十进制数)。 What I want to do is get just whatever value is inside the
<span></span>
. 我想要做的就是获得
<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.
我尝试过使用^和$以及“m”多线修改器的变体,但没有运气。
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 (ie it's not the DOM we're dealing with at this point). 如果有一种方法可以在字符串中定位span标记,那么我可以在这里使用jQuery(也就是说,这不是我们此时正在处理的DOM)。
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. 使用jQuery非常简单。 Simply wrap your HTML string inside a div and use jQuery as usual:
只需将HTML字符串包装在div中并像往常一样使用jQuery:
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 编辑:既然你使用字符串来定义你的正则表达式,不要忘记esacpe你的反斜杠,所以
[\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/ 在这里测试: http : //jsfiddle.net/9LQGK/
The matches
array will contain the matches. 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? 什么
there's potentially two numbers and I want to ignore the first one
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.