这个JavaScript函数是如何工作的
我正在读一些关于学校的教程 我右键单击并查看页面源代码,在源代码中找到此函数:这个JavaScript函数是如何工作的,javascript,Javascript,我正在读一些关于学校的教程 我右键单击并查看页面源代码,在源代码中找到此函数: function submitTryit() { var t = document.getElementById("textareaCode").value; t = t.replace(/=/gi, "w3equalsign"); var pos = t.search(/script/i) while (pos > 0) { t = t.substring(0,
function submitTryit() {
var t = document.getElementById("textareaCode").value;
t = t.replace(/=/gi, "w3equalsign");
var pos = t.search(/script/i)
while (pos > 0) {
t = t.substring(0, pos) + "w3" + t.substr(pos,3)
+ "w3" + t.substr(pos+3,3) + "tag" + t.substr(pos+6);
pos = t.search(/script/i);
}
document.getElementById("code").value = t;
document.getElementById("tryitform").action = "tryit_view.asp?x=" + Math.random();
validateForm();
document.getElementById("tryitform").submit();
}
function validateForm() {
var code = document.getElementById("code").value;
if (code.length > 5000) {
document.getElementById("code").value = "<h1>Error</h1>";
}
}
这有什么用
var pos = t.search(/script/i)
t = t.substring(0, pos) + "w3" + t.substr(pos,3)
+ "w3" + t.substr(pos+3,3) + "tag" + t.substr(pos+6);
似乎t
是文本区域的值,也就是说,无论用户在所述文本区域中输入了什么
t.search(/script/)
它使用正则表达式在用户输入的任何内容中搜索字符“script”
t.search(/script/i)
i
标志使其不区分大小写(以便与“Script”、“Script”等匹配)
这会将第一个匹配的位置分配给变量pos
alert("StackOverflow Rocks!".search(/rock/i));
将提醒“14”,因为这是第一场比赛的位置
如果没有找到匹配项,则search
返回-1语法
/script/i
创建一个以不区分大小写的方式匹配字符“script”(即它将匹配“script”
,“script”
,“script”
,等等)。这一行:
var pos=t.search(/script/i)
将pos
设置为字符“script”在t
中第一次出现的位置,不考虑大小写。(如果t
不包含匹配的字符序列,则将pos
设置为-1。)
您询问的另一行:
t=t.substring(0,pos) + "w3" + t.substr(pos,3) + "w3" + t.substr(pos+3,3) + "tag" + t.substr(pos+6);
将找到的“script”序列替换为字符“w3scrw3ipttag”(同时在原始字符串中保留“script”的大小写)
请不要问我他们为什么这样做。另外,请不要试图通过阅读站点源代码来学习JavaScript。(至少在你掌握了基础知识之前,甚至在那时……很多都很糟糕。)相反,花时间阅读一些非常好的东西。我建议你搜索并查看web上已有的官方文档:你是否在W3School的帮助下学习javascript,或者尝试实现与W3School相同的功能?如果您只是在学习js,那么就不需要查看w3school网站的源代码。
var pos=t.search(/script/i)
t=t.substring(0,pos) + "w3" + t.substr(pos,3) + "w3" + t.substr(pos+3,3) + "tag" + t.substr(pos+6);