javascript url.indexOf等于不包含

时间:2018-08-22 17:25:11

标签: javascript url equals

我有这个问题: 我用这个:

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;}

1 个答案:

答案 0 :(得分:0)

如评论中所述,寻找完全匹配可能是最安全的。您可以使用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);
}