用Regex来查找内联脚本中是否存在jQuery的引用。

问题描述 投票:1回答:1

我想创建一个regex模式,检查 "jQuery "是否存在于介于 <script></script> 标签。

例如,我想出了以下的regex

<script>

 function foo(jQuery){
   alert("i take jQuery in as a parameter!");
 }

</script>

我想出了以下的regex。

/(?s)(<script>.*?jQuery.*?<\/script>)/

如果只有一个脚本块,这似乎很好,如果有多个脚本(其中一个包含jQuery),那么regex就会匹配第一个脚本块和第二个脚本块之间的所有内容。 <script> 而最后 </script> 标签。

<script> <-- Match starts
  const i = "foo";
</script> <-- no jQuery referenced in this script block...

<p>Hi!</p>

<script>
 console.log(jQuery);
</script> <-- Match ends

它应该是这样的

<script> <-- Match starts
 console.log(jQuery);
</script> <-- Match ends

<script>
  const i = "foo";
</script>

<p>Hi!</p>

<script> <-- Match starts
 console.log(jQuery);
</script> <-- Match ends
regex regex-group regex-greedy
1个回答
0
投票

你可以尝试使用正向的lookahead,但不使用 (?s)诸如此类

<script>.*?\r?\n?(?=jQuery)((?:.*?\r?\n?)*)<\/script>

演示1

© www.soinside.com 2019 - 2024. All rights reserved.