有人可以帮我解释这个JavaScript正则表达式吗?
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ')
Run Code Online (Sandbox Code Playgroud)
Ric*_*dle 11
( Either
^ the start of the string
| or
\\s+ one or more whitespace characters
) followed by
className the class name in question
( followed by either
\\s+ one or more whitespace characters
| or
$ the end of the string
)
Run Code Online (Sandbox Code Playgroud)
所以它将匹配"pog":
"pog"
" pog"
"pog "
"pog bim"
"bim pog"
" pog bim"
"bim pog "
"bim pog pam"
Run Code Online (Sandbox Code Playgroud)
等等
new RegExp()可以给出选项的第二个参数,例如."我"的意思是"不区分大小写".在你的情况下,你没有传递任何选项(如果你正在处理HTML类名,这是正确的 - 类名应该区分大小写).
RichieHindle有一个很好的答案.我只是想添加一些关于这种模式的目的的信息.
当您检查元素是否具有给定的CSS类时,您希望避免误报.如果你的正则表达式太简单了,就像这样
var pattern = new RegExp( className );
Run Code Online (Sandbox Code Playgroud)
然后,具有类"fooBar"的元素将对类"foo"的检查测试为正.这里存在这些边界子模式以防止这种情况.这是它的实际演示
<div id="test1" class="red big">My class is "red big"</div>
<div id="test2" class="red-and-big green">My class is "red-and-big green"</div>
<textarea id="output" rows="10" cols="60"></textarea>
<script type="text/javascript">
var ta = document.getElementById( 'output' );
var test1 = document.getElementById( 'test1' );
var test2 = document.getElementById( 'test2' );
function hasCssClass( classList, className )
{
var pattern = new RegExp( "(^|\\s+)" + className + "(\\s+|$)" );
return pattern.test( classList );
}
function testElement( elem, className )
{
var has = hasCssClass( elem.className, className )
ta.value += elem.id + ' ' + ( has ? 'has' : 'does not have' ) + ' ' + className + "\n";
}
testElement( test1, 'red' );
testElement( test1, 'green' );
testElement( test1, 'big' );
testElement( test1, 'red-and-big' );
testElement( test2, 'red' );
testElement( test2, 'big' );
testElement( test2, 'green' );
testElement( test2, 'red-and-big' );
</script>
Run Code Online (Sandbox Code Playgroud)