Javascript新的RegExp vs. / pattern /和多行 [英] Javascript new RegExp vs. /pattern/ and multi line

查看:52
本文介绍了Javascript新的RegExp vs. / pattern /和多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么/ pattern /匹配,但RegExp不是?

Why is the /pattern/ matching, but the RegExp not?

<div id="foo">
##content##
<h1>works!</h1>
##/content##
</div>

<script>
var str = document.getElementById("foo").innerHTML;
console.log(str);

var r = new RegExp("##content##([\S\s]*)##\/content##", "img");

console.log(r.exec(str)); //null
console.log(str.match(/##content##([\S\s]*)##\/content##/img)); //matches
</script>


推荐答案

问题是这一行:

var r = new RegExp("##content##([\S\s]*?)##\/content##", "img");

应替换为:

var r = new RegExp("##content##([\\S\\s]*?)##\/content##", "img");

原因:了解RegExp对象将String作为参数来构造和您需要双重转义 \S \s 以便RegEx引擎正确解释所以 \S 应该变成 \\\\ 而\ s应该变成 \\\\ 在你的正则表达式中。

Reason: Understand that RegExp object takes a String as argument to construct and you need to double escape \S and \s to be correctly interpreted by RegEx engine so \S should become \\S and \s should become \\s in your regex.

这篇关于Javascript新的RegExp vs. / pattern /和多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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