javascript - javascript url.indexOf 等于不包含
问题描述
我有这个问题:我用这个:
url.indexOf('RpId=2') > -1
但是当 RpId=27 或 28 时,我正在制作的页面也会发生。我需要它具体为 2,而不是“包含 2”。
总脚本是:
<script type="text/javascript">
$(document).ready(function(){
var url = document.location.href;
if( !(url.indexOf('RHViewStoryBoard.aspx') > -1 && (
url.indexOf('RpId=31') > -1 || url.indexOf('RpId=35') > -1 || url.indexOf('RpId=6') > -1 || url.indexOf('RpId=34') > -1 || url.indexOf('RpId=30') > -1 || url.indexOf('RpId=11') > -1|| url.indexOf('RpId=2') > -1 ) ) ){
$('body').append('<style type="text/css">html body .customSlidesNav.customSlidesNavNext {display:block !important}html body .customSlidesNav.customSlidesNavNext {display:block !important}</style>')
}
});
</script>
我有一些 css 可以使用:
html .customSlidesNav.customSlidesNavNext {display: none !important;}
html .customSlidesNav.customSlidesNavPrev {display: none !important;}
解决方案
正如评论中所说,寻找完全匹配可能是最安全的。您可以使用urlSearchParams来解析查询字符串。此外,您可以使用一组有效的 rpid 来缩短它,而不是长的 if 语句。这是一个例子:
let url = new URL('https://www.example.com/apath?query1=test&RpId=2&test2=test');
let searchParams = new URLSearchParams(url.search);
let rpid = searchParams.get("RpId");
const validRpids = ["31", "35", "6", "34", "30", "11", "2"];
// do any condition you want with RpId
// don't forget to parse RpId if you want to do something with the number and not a string
if(validRpids.includes(rpid)){
console.log("rpid is valid: " + rpid);
}
else{
console.log("rpid is NOT valid: " + rpid);
}
推荐阅读
- javascript - Console.table 显示不带引号的字符串
- reactjs - 如何使用 Yup 验证一个字段与另一个字段?
- angular - 如何在 Angular 中将值从 .ts/html 传递到 css/scss?
- join - 将两个分区表合并为一张表,但合并为两个不同的分区
- wcf - System.Net.Sockets.SocketException:现有连接被远程主机强行关闭
- flutter - 为 CircleAvatar wiget (Flutter) 隐藏溢出
- numpy - 根据条件重塑神经网络输入
- java - 处理时间加倍的功能问题
- graphql - GraphQL 错误 FieldsConflict:字段具有不同的列表形状
- angular - 如何在不使用异步等待的情况下在 Angular 中的订阅中获取价值