programing

는 URL은 주어진 문자열이 포함되 어떻게 확인해야 하죠?

procenter 2022. 9. 21. 22:33
반응형

는 URL은 주어진 문자열이 포함되 어떻게 확인해야 하죠?

어떻게:이 일을 할 수 없다

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

당신은href 재산과 수표습니다.indexOf대신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)

그가 할 것이다.또는:regexp 사용할 수 있다.

if (/franky/.test(window.location.href))

이런:indexOf을 사용할 것입니다.

if(window.location.href.indexOf("franky") != -1){....}

추가에 주의해 주세요.href그렇지 않으면 다음 작업을 수행합니다.

if(window.location.toString().indexOf("franky") != -1){....}

Window.location은 String,지만 a다toString()방법.다음과 같이 할 수 있습니다.

(''+window.location).includes("franky")

또는

window.location.toString().includes("franky")

오래 된 모질라 도움말:부터.

위치 물체. 당신은 또한 window.location는 문자열을 할당할 수 있는toString 메서드가 현재 URL 돌아오고 있다.이 대부분의 경우에 마치 문자열이 window.location로 작업을 할 수 있다는 것을 의미한다.가끔은 당신이 String메서드 호출해야 할 예를 들어 명시적으로 toString에게 전화를 걸어야 해.

다음과 같이 합니다.

    <script type="text/javascript">
        $(document).ready(function () {
            if(window.location.href.indexOf("cart") > -1) 
            {
                 alert("your url contains the name franky");
            }
        });
    </script>

정규식 방법:

var matches = !!location.href.match(/franky/); //a boolean value now

또는 다음과 같은 간단한 설명을 사용할 수 있습니다.

if (location.href.match(/franky/)) {

웹 사이트가 로컬에서 실행 중인지 서버에서 실행 중인지 테스트하기 위해 사용합니다.

location.href.match(/(192.168|localhost).*:1337/)

그러면 href에 다음 중 하나가 포함되어 있는지 여부가 체크됩니다.192.168또는localhostAND 뒤에:1337.

보시다시피 상황이 좀 까다로워질 때 regex를 사용하면 다른 솔루션보다 이점이 있습니다.

document.URL당신에게 줄 수 있을 것입니다URL그리고.

if(document.URL.indexOf("searchtext") != -1) {
    //found
} else {
    //nope
} 

이거 해봐, 더 짧고 정확하게 동작해.window.location.href:

if (document.URL.indexOf("franky") > -1) { ... }

또한 이전 URL을 확인하는 경우:

if (document.referrer.indexOf("franky") > -1) { ... }

간단해

<script type="text/javascript">
$(document).ready(function () {
    var url = window.location.href;
    if(url.includes('franky'))    //includes() method determines whether a string contains specified string.
    {
         alert("url contains franky");
    }
});
</script>

indexof() 메서드는 대소문자를 구분하므로 문자열을 lower 또는 대문자로 변환하는 것이 좋습니다.

이는 검색에서 대소문자를 구분하지 않는 경우 orignal 문자열을 소문자나 대문자로 변환하지 않고 indexOf() 메서드를 사용할 수 있습니다.

var string= location.href;
var convertedString= string.toLowerCase();

if(convertedString.indexOf('franky') != -1)
{
    alert("url has franky");
}
else
{
    alert("url has no franky");
}

이것을 시험해 보세요.

<script type="text/javascript">             
    $(document).ready
    (
        function () 
        { 
            var regExp = /franky/g;
            var testString = "something.com/frankyssssddsdfjsdflk?franky";//Inyour case it would be window.location;
            if(regExp.test(testString)) // This doesn't work, any suggestions.                 
            {                      
                alert("your url contains the name franky");                 
            }             
        }
    );         
</script> 

색인 사용

if (foo.indexOf("franky") >= 0)
{
  ...
}

(정규 표현의 경우) 검색을 시도할 수도 있습니다.

if (foo.search("franky") >= 0)
{
  ...
}

대신 이 방식이 마음에 들어요.

top.location.pathname.includes('franky')

그것은 많은 경우에 효과가 있다.

Window.location을 사용합니다.href를 지정하여 javascript의 URL을 가져옵니다.브라우저의 현재 URL 위치를 알려주는 속성입니다.속성을 다른 것으로 설정하면 페이지가 리디렉션됩니다.

if (window.location.href.indexOf('franky') > -1) {
     alert("your url contains the name franky");
}

작성하기를 원합니다.boolean그리고 그걸 논리적으로 사용해서if.

//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);

if (!onLoginPage) {
  console.log('redirected to login page');
  window.location = "/login";
} else {
  console.log('already on the login page');
}

js 파일을 넣습니다.

                var url = window.location.href;
                console.log(url);
                console.log(~url.indexOf("#product-consulation"));
                if (~url.indexOf("#product-consulation")) {
                    console.log('YES');
                    // $('html, body').animate({
                    //     scrollTop: $('#header').offset().top - 80
                    // }, 1000);
                } else {
                    console.log('NOPE');
                }

정규 표현은 단어 경계 때문에 많은 사람들에게 더 적합합니다.\b또는 유사한 디바이스입니다.단어 경계는 다음 중 하나에 해당하는 경우 발생합니다.0-9,a-z,A-Z,_는 다음 일치의 반대쪽에 있거나 영숫자가 회선, 문자열 끝 또는 선두에 연결되어 있는 경우입니다.

if (location.href.match(/(?:\b|_)franky(?:\b|_)))

「 」를 사용하고 if(window.location.href.indexOf("sam")하다'와flotsam ★★★★★★★★★★★★★★★★★」same그 중에서도. tom'regex', 'regex', 'regex', 'regex',

은 '대소문자를 구분하는 것'을.i.

또한 다른 필터를 추가하는 것은 다음과 같이 간단합니다.

if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i))

이번에는 ㅇㅇㅇㅇㅇㅇㅇㅇ에 요?(?:\b|_)으로 . RegEx를 정의합니다._word character단어 경계선을 만들지 않습니다.요.(?:\b|_)이 문제를 해결하려고요. 중 하나를 찾을 수 하기 위해\b ★★★★★★★★★★★★★★★★★」_현의 양쪽에 있습니다.

다른 언어에서는 다음과 같은 것을 사용해야 할 수 있습니다.

if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i))
//where xxx is a character representation (range or literal) of your language's alphanumeric characters.

이 모든 것은 말하는 것보다 쉽다.

var x = location.href // just used to shorten the code
x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam")...
// and other comparisons to see if the url ends with it 
// more for other filters like frank and billy

맛 은 를 지원합니다.\p{L}이 훨씬.[^\p{L}](filters|in|any|alphabet)[^\p{L}]

창 로케이션은 여러 메서드를 포함하는 개체로, 이들 중 일부는 URL과 관련된 문자열이므로 타깃 문자열을 안전하게 검색할 수 있습니다.

const href = location.href;
// "https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string"

// another option 
const pathname = location.pathname;
// "/questions/4597050/how-to-check-if-the-url-contains-a-given-string"

// search for string safely
pathname.includes("questions"); // true
href.includes("questions"); // true

로케이션 오브젝트

이 스크립트가 있다고 가정합니다.

<div>
  <p id="response"><p>
  <script>
    var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
    var text_input = query.split("&")[0].split("=")[1];
    document.getElementById('response').innerHTML=text_input;
  </script> </div>

은 url 입니다.www.localhost.com/web_form_response.html?text_input=stack&over=flow

<p id="response"> 되다stack

이건 내 코드야 ♥

function CheckUrl(url) {
var checkA = url.match(/(https|http):\/\/(.*?)\.(.*?)\.(.*?)(\/|'')/g);
var checkP = url.match(/(https|http):\/\/(.*?)\.(.*?)(\/|'')/g);
if (checkA != null || checkP != null) {
    return true;
}
else {
    console.log("Error", "The link is not valid");
}
return false;}

javascript 문자열 방식 일치를 사용할 수 있습니다.

const url = window.location.href;
const find = 'questions';
const found = url.match(find);

console.log(url);

if(found !== null && found[0] === find){
  console.log('You are in the questions page');
} else {
  console.log('You are not in the questions page');
}

언급URL : https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string

반응형