如何检查URL是否包含给定的字符串?

时间:2011-01-04 18:31:05

标签: javascript jquery 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>

19 个答案:

答案 0 :(得分:576)

您需要添加href属性并检查indexOf而不是contains

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

答案 1 :(得分:88)

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

会这样做。或者,您可以使用正则表达式:

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

答案 2 :(得分:21)

像这样:

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

答案 3 :(得分:20)

您可以像这样使用indexOf

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

另请注意为字符串添加href,否则您会这样做:

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

答案 4 :(得分:11)

window.location不是String,但它有toString()方法。所以你可以这样做:

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

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

来自old Mozilla docs

  

位置对象有一个toString   返回当前URL的方法。您   也可以指定一个字符串   window.location的。这意味着你   可以使用window.location,就像它一样   在大多数情况下是一个字符串。   有时,例如在您需要时   你可以调用一个String方法   必须显式调用toString。

答案 5 :(得分:8)

正则表达方式:

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

或者在一个简单的陈述中你可以使用:

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

我用它来测试网站是在本地运行还是在服务器上运行:

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

检查 href 是否包含192.168localhost并且后跟:1337

正如您所看到的,当条件变得有点棘手时,使用正则表达式优于其他解决方案。

答案 6 :(得分:6)

document.URL应该为您提供URL

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

答案 7 :(得分:6)

试试这个,它更短,与window.location.href完全相同:

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

如果您想查看以前的网址,也可以

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

答案 8 :(得分:4)

更容易获得

JavaPairRDD<IntWritable,VectorWritable> RDDwith1000 = sc.parallelize(seqVectors.take(1000));

答案 9 :(得分:3)

尝试indexOf

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

您也可以尝试搜索(正则表达式)

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

答案 10 :(得分:3)

试试这个:

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

答案 11 :(得分:2)

我想创建一个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');
}

答案 12 :(得分:2)

如果将字符串转换为小写或大写,这是一个好习惯,因为indexof()方法区分大小写。

如果您的搜索不区分大小写,则只需使用indexOf()方法,而无需将原始字符串转换为小写或大写即可。

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

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

答案 13 :(得分:1)

  

使用Window.location.href在javascript中获取url。它是一个   将告诉您浏览器当前URL位置的属性。   将属性设置为不同的属性将重定向页面。

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

答案 14 :(得分:1)

放入你的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');
                }

答案 15 :(得分:1)

由于字边界\b或类似设备,正则表达式对于很多人来说会更加优化。当0-9a-zA-Z_中的任何一个位于下一场比赛的那边或者字母数字字符时,就会出现字边界连接到行或字符串结尾或开头。

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

如果您使用if(window.location.href.indexOf("sam"),则会获得flotsamsame的匹配项。 tom会匹配番茄,明天会匹配正则表达式。

使其区分大小写就像删除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},但javascript不支持,这将使检测外来字符的任务变得更加容易。像[^\p{L}](filters|in|any|alphabet)[^\p{L}]

这样的东西

答案 16 :(得分:0)

假设您有此脚本

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

网址格式为www.localhost.com/web_form_response.html?text_input=stack&over=flow

写入<p id="response">的文字为stack

答案 17 :(得分:0)

相反,我喜欢这种方法。

import React, { useState, } from 'react';
import { useGlobalContext } from '../Context'
import { Link } from 'react-router-dom';
import { Button, Grid, Typography, TextField, FormHelperText, FormControl, Radio, RadioGroup, FormControlLabel } from '@material-ui/core'

function CreateRoom() {
    const defaultVotes =  2;
    const { handleGuestCanPauseChange, handleVotesChange, handleRoomButtonPressed } = useGlobalContext();

    return (
        <Grid container spacing={1}>
            <Grid item xs={12} align="center">
                <Typography component="h4" variant="h4">
                    Create A Room
                </Typography>
            </Grid>
            <Grid item xs={12} align="center">
                <FormControl component="fieldset">
                    <FormHelperText>
                        <div align="center">Guest Control of Playback state</div>
                    </FormHelperText>
                    <RadioGroup row defaultValue="true" onChange={handleGuestCanPauseChange}>
                        <FormControlLabel value="true" 
                        control={<Radio color="primary" />}
                        label="Play/Pause" labelPlacemment="bottom" />
                        <FormControlLabel value="false" 
                        control={<Radio color="secondary" />}
                        label="No Control" labelPlacemment="bottom" />
                    </RadioGroup>
                </FormControl>
            </Grid>
            <Grid item xs={12} align="center">
                <FormControl>
                    <TextField required={true}
                    type="number" onChange={handleVotesChange}
                    defaultValue={defaultVotes} 
                    inputProps={{ min: 1,
                        style: { textAlign: "center" },
                        }}
                    />
                    <FormHelperText>
                    <div align="center">Votes Required To Skip Song</div>
                    </FormHelperText>
                </FormControl>
            </Grid>
            <Grid item xs={12} align="center">
            <Button
                color="primary"
                variant="contained"
                onClick={handleRoomButtonPressed}
            >
                Create A Room
            </Button>
            </Grid>
            <Grid item xs={12} align="center">
            <Button color="secondary" variant="contained" to="/" component={Link}>
                Back
            </Button>
            </Grid>
        </Grid>
    )
}

export default CreateRoom

它适用于许多情况。

答案 18 :(得分:0)

窗口位置是一个包含多个方法和道具的对象,其中一些是与 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

The Location Object

相关问题