有段JS代码搞不清楚,求高手进来解答一下

来源:百度知道 编辑:UC知道 时间:2024/05/28 22:21:26
removeClass = function(target, theClass)
{
var pattern = new RegExp("(^| )" + theClass +"( |$)");

target.className = target.className.replace(pattern, "$1");
target.className = target.className.replace(/ $/,"");
};

问题有这些:
target.className = target.className.replace(pattern, "$1");中的"$1"代表什么。
target.className = target.className.replace(/ $/,"");中的/ $/又代表什么意思,整个的(/ $/,"")是什么意思。

这些是正则表达式替换!

1. target.className = target.className.replace(pattern, "$1");中的"$1"代表什么。
这个代表把字串里符合pattern规则的串都替换成$1
这个pattern的规则就是:以"| "开头,以" |"结束,中间包含theClass的行

2. target.className = target.className.replace(/ $/,"");中的/ $/又代表什么意思,整个的(/ $/,"")是什么意思

这个/ $/代表以“ ”空格结束的串,
整个的(/ $/,"")代表要把以“ ”空格结束的串最后的空格都去掉,就是:
“ABC ”替换成“ABC”,但不是“AB C”替换成“ABC”