gpt4 book ai didi

javascript - 如何使用 JAVASCRIPT/正则表达式从字符串中找到 "<script>"标签

转载 作者:数据小太阳 更新时间:2023-10-29 03:58:26 26 4
gpt4 key购买 nike

我需要为文本 <script 验证传入的字符串.

例子:
string a = "This is a simple <script> string";

现在,我需要编写一个正则表达式来告诉我这个字符串是否包含 <script>标记与否。

我最后写了类似这样的东西:<* ?script.* ?>

但挑战在于,传入的字符串可能包含以下方式的脚本,

string a = "This is a simple <script> string";
string a = "This is a simple < script> string";
string a = "This is a simple <javascript></javascript> string";
string a = "This is a simple <script type=text/javascript> string";

因此正则表达式应该检查开始 <标记,然后它应该检查 script .

最佳答案

采用:

/<script[\s\S]*?>[\s\S]*?<\/script>/gi

@bodhizero 接受的关于 <[^>]*script 的回答错误地返回 true在以下条件下:

// Not a proper script tag.
const a = "This is a simple < script> string";

// Space added before "img", otherwise the entire tag fails to render here.
const a = "This is a simple < img src='//example.com/script.jpg'> string";

// Picks up "nonsense code" just because a '<' character happens to precede a 'script' string somewhere along the way.
const a = "This is a simple for(i=0;i<5;i++){alert('script')} string";

Here is an excellent resource for building and testing regular expressions .

关于javascript - 如何使用 JAVASCRIPT/正则表达式从字符串中找到 "&lt;script&gt;"标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16585635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com