Javascript正则表达式替换,多行 [英] Javascript regexp replace, multiline

查看:112
本文介绍了Javascript正则表达式替换,多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文本内容(使用jQuery从HTML中读取),看起来像这些示例之一:

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

这些数字可以格式化为


  • 1,234.99

  • 1239,99

  • 1 239,99

等(即不仅仅是正常的十进制数)。我想要做的是获得< span>< / span> 中的任何值。

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

这是我到目前为止所提出的问题,但我遇到了多线方法的问题,以及可能存在两个数字并且我想忽略第一个数字的事实。我尝试过使用^和$以及m多线修改器的变体,但没有运气。

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');

如果有办法在字符串中定位span标签,我可以在这里使用jQuery(即它不是我们此时正在处理的DOM。)

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

推荐答案

尝试使用

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

而不是

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

编辑:因为你正在使用一个字符串来定义你的正则表达式,所以不要忘记esacpe你的反斜杠,所以

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

[\s\S] 

[\\s\\S]

这篇关于Javascript正则表达式替换,多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆