我试图在JS中使用正则表达式,但我可能遗漏了一些东西,因为我无法让它工作。我有两个正则表达式在PHP中很好地工作(与preg_match一起使用),但是当我在JS中使用完全相同的表达式时,我没有得到匹配的模式。
下面是一个例子,我试图解析这个页面:
https://www.coolblue.be/fr/rechercher?query=GTX+1060&trier=prix-les-moins-chers我的代码:
var pattern = '/<a class=\"product__title js-product-title\" href=\"(.*)\" data-trackclickevent=\"(.*)\">[\n\r\s]+(.*)[\n\r\s]+<\/a>/gi';
var found = content.match(pattern);变量内容包含页面的完整源代码,我已将其转储到控制台中,以确保其正常工作,例如:(代码很脏,但我从上面提到的页面中获取了它,没有更改任何内容)
<div class="product__titles"><div class="js-product-feature-title"></div><a class="product__title js-product-title" href="/fr/produit/654109" data-trackclickevent="Internal Search, Product, Oehlbach BTX 1000 (654109) - Product title">
Oehlbach BTX 1000
</a></div><div class="product__review-rating"><div class="review-rating alt-compact"><div class="review-rating--rating">当我使用https://regex101.com/测试我的正则表达式时,它也能工作,但在JS中却不起作用。
知道我错过了什么吗?
谢谢
洛朗
发布于 2018-02-17 16:55:23
好吧,我就是这样解决这个问题的。
var el = document.createElement( 'html' );
el.innerHTML = content;
all_links = el.getElementsByClassName("product__title");内容需要包含html
发布于 2018-02-17 16:54:16
在JavaScript中,您将主要在两种方法中使用正则表达式:测试和替换。虽然test只是告诉您它的参数是否与正则表达式匹配,但替换使用第二个参数:用于替换匹配的文本的字符串。就像大多数函数一样,替换作为返回值生成一个新的字符串;它不改变输入例如;
document.write(/cats/i.test("Cats are fun. I like cats."));并替换:
document.write("Cats are fun. I like cats.".replace(/cats/gi,"dogs"));
也是在Javascript中,你必须避开下面的近括号“];
\[([^\]\s]+).([^\]]+)\]
https://stackoverflow.com/questions/48842915
复制相似问题