首页 > 解决方案 > 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;}

标签: javascripturlequals

解决方案


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


推荐阅读