Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字符串是html还是选择器?javascript_Javascript_Html_Regex_String_Selector - Fatal编程技术网

字符串是html还是选择器?javascript

字符串是html还是选择器?javascript,javascript,html,regex,string,selector,Javascript,Html,Regex,String,Selector,我从这里获取了一些代码:--并对其进行了一些修改。但是,我无法使火柴正常工作。我试过.test和.exec var htmlExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/; if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >

我从这里获取了一些代码:--并对其进行了一些修改。但是,我无法使火柴正常工作。我试过
.test
.exec

var htmlExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/;
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 || htmlExpr.test( selector )) {
    return true;
} else {
    return false;
}
var htmlExpr=/^(?:[^]*$|#([\w\-]+)$)/;
if(selector.charAt(0)==“&&selector.length>=3 | | htmlExpr.test(选择器)){
返回true;
}否则{
返回false;
}
我正在使用
#mydiv
galleryblah
作为
选择器

两者都返回true

这里发生了什么,我遗漏了?

\mydiv
返回true,因为您在这部分的正则表达式中特别检查了它
|#([\w\-]+)$
,您应该删除该部分,以便
\mydiv
不匹配,如下所示:

var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/;
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 || htmlExpr.test( selector )) {
    return true;
} else {
    return false;
}
var htmlExpr=/^[^]*$/;
if(selector.charAt(0)==“&&selector.length>=3 | | htmlExpr.test(选择器)){
返回true;
}否则{
返回false;
}

请参见“工作”

为什么要尝试此操作?我不确定这是否可能与正则表达式,我看不到任何可能的用途。请注意,您使用的答案是关于测试字符串是否为HTML,这与您在此处编写的相反。在
if
语句中,您为什么同时使用这两种方法?在您提供的SO问题中,答案是使用regex或
charAt
&
length
方法。为什么要在末尾添加
htmlExpr.test(selector)
?@dystroy jQuery使用它来确定作为初始参数传入的字符串是选择器还是字符串。还有一个更复杂的问题,我在一个小型的内部库更新中有一个简单的用例,这是必要的。@Ian javascript应该在匹配完成后立即执行内容。即,如果第一个值为真,则忽略第二个值(在
|
之后)。因此,问题是根据哪个评估成功返回两个不同的值。我不在乎这里哪一个是成功的,只有一个是。@RandyHall两个选择器中哪一个不应该返回true?现在两个字符串都返回false=/^(?:[^]*$|([\w\-]+$)/,至少对这两种情况都是有效的!接得好(我的正则表达式很差)。