如何检查字符串是否包含'?'使用javascript

时间:2016-06-16 09:21:53

标签: javascript

我试图检查网址是否包含查询字符串。 可以说我们有这两个网址。

http://localhost:3000/userbookings/list

http://localhost:3000/userbookings/list?resource=de

我的字符串被称为fullPath,我需要检查它是否包含?,所以我知道它是否是一个查询字符串。

尝试使用以下代码:

if (fullPath.indexOf("?") > -1){
    content = fs-readFileSync('http://localhost:3000/userbookings/list1');
}
else {
    content = fs.readFileSync(fullPath);
}

4 个答案:

答案 0 :(得分:0)

像这样:

if (str.indexOf("?") >= 0)

或者,

if (/\?/i.test(str))

或者,

if(str.includes('?'))

请注意,String.includes是一项EcmaScript 6功能,可能无法在某些浏览器中使用。

答案 1 :(得分:0)

你的方式也应该有效,但如果你希望将来使用更复杂的限定符,你可以开始使用正则表达式:

var pattern = /\?/g;
var found = fullPath.match(pattern) != null;
alert(found);

答案 2 :(得分:0)

这有助于你:

    <html>
    <head>
    </head> 
        <body>
           <script>
               var str = "this is ?text";
               var patt = /\?/gi;
               if(str.search(patt)!=-1)
                   alert("Found");
               else
                   alert("No found");
            </script>
        </body>
        
    </html>

答案 3 :(得分:0)

我认为你的目标只是检查是否有一个php get变量?

if(document.localtion.search != "") {
   // Your code
}

如果您访问网址

,document.location.search将为“?resource = de”

http://localhost:3000/userbookings/list?resource=de

如果您访问网址

将会是“”

http://localhost:3000/userbookings/list

回答#2

check = document.location.split("?");

    if(check.length > 1) {
       //do your code
    }

使用“?”拆分http://localhost:3000/userbookings/list?resource=de网址将被2分割。

使用“?”拆分http://localhost:3000/userbookings/list网址结果由1。

回答#3

check = fullpath.replace("?","");
if(check != fullpath) {
   //do your code
}

删除“?”在完整的道路上。如果检查与完整路径相同,则它没有“?”

我认为这可能会帮助你。随意发表评论