어떻게 이런 식으로 할 수 있습니까?
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
답변
indexOf
대신 href 속성을 추가하고 확인해야합니다.contains
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if (window.location.href.indexOf("franky") > -1) {
alert("your url contains the name franky");
}
});
</script>
답변
if (window.location.href.indexOf("franky") != -1)
할 것입니다. 또는 정규 표현식을 사용할 수 있습니다.
if (/franky/.test(window.location.href))
답변
다음 indexOf
과 같이 사용 하십시오.
if(window.location.href.indexOf("franky") != -1){....}
href
그렇지 않으면 문자열을 추가하는 것에 주목하십시오 .
if(window.location.toString().indexOf("franky") != -1){....}
답변
이렇게 :
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("cart") > -1)
{
alert("your url contains the name franky");
}
});
</script>
답변
window.location
String은 아니지만 toString()
메소드가 있습니다. 따라서 다음과 같이 할 수 있습니다.
(''+window.location).includes("franky")
또는
window.location.toString().includes("franky")
로부터 오래된 모질라 문서 :
위치 객체에는 현재 URL을 반환하는 toString 메소드가 있습니다. window.location에 문자열을 할당 할 수도 있습니다. 이는 대부분의 경우 문자열 인 것처럼 window.location으로 작업 할 수 있음을 의미합니다. 예를 들어, String 메소드를 호출해야하는 경우 명시 적으로 toString을 호출해야합니다.
답변
정규식 방법 :
var matches = !!location.href.match(/franky/); //a boolean value now
또는 간단한 문장으로 다음을 사용할 수 있습니다.
if (location.href.match(/franky/)) {
웹 사이트가 로컬로 실행 중인지 서버에서 실행 중인지 테스트하는 데 사용합니다.
location.href.match(/(192.168|localhost).*:1337/)
이것은 href 가 AND를 포함 하는지 192.168
또는 localhost
AND가 뒤에 오는지 점검합니다 :1337
.
보시다시피, 정규 표현식을 사용하면 조건이 조금 까다로울 때 다른 솔루션보다 장점이 있습니다.
답변
document.URL
당신 URL
과
if(document.URL.indexOf("searchtext") != -1) {
//found
} else {
//nope
}
