繁体   English   中英

如何从URL获取值?

[英]How can I get a value from an URL?

假设我有类似的东西

var url = 'http://stackoverflow.com/questions/24a34b83c72/js-regex-get-values-between-two-characters'

如何使用纯javascript获取24a34b83c72 ID? 我知道它总是在questions/部分之后,无论它是否包含数字或符号,它都需要在下一个/之前结束。 我尝试过这样的事情;

url.substring(url.lastIndexOf('questions/'))

但这导致了整个线程。 我尝试了正常的表达,但我最接近的是:

var regex = /"details\\/"[a-zA-Z0-9]+"\\/"/

谁能帮我?

您可以在questions/之后questions/在下一个/之前对所有内容进行分组,如下所示:

url.match(/questions\/([^/]+)/)[1]

你可以看到url.match(..)的输出是这样的:

["questions/24a34b83c72", "24a34b83c72"]

第二项是因为[^/]+周围的括号,所以你用url.match(..)[1]访问它。

正则表达式对于更复杂的模式或重复匹配很有用。 您的要求简单而单一。

'/'拆分字符串,找到'questions'的索引,结果在下一个索引中:

var parts = url.split('/');
var result = parts[parts.indexOf('questions') + 1];

如果你坚持regexp:

questions\/([0-9A-Za-z]+?)\/

https://regex101.com/r/dE1oC7/1

这应该与作为示例提供的字符串匹配。

这对我有用,你的示例在Firefox控制台上:

    >> var url = 'http://stackoverflow.com/questions/24a34b83c72/js-regex-   get-values-between-two-characters'
    >> var regex = /questions\/([a-zA-Z0-9]+)\//
    >> regex.exec(url)

    Array [ "questions/24a34b83c72/", "24a34b83c72" ]

数组的第二个元素应该是您正在寻找的。

[另外一个选项]

我首先解释URL字符串,然后解释解释为我返回的内容( 作为 Abtract语法树 )。 以下命令块将在下面的循环执行(或解释 )时使用url字符串,逐步构建代表性数组!

var curChar,
    directoryPassed,//not yet
    expectGetValue,
    getContent="",
    getStarted,//? not started ($_GET)
    inPort,//not reading port
    portRead,//port not read yet
    state=0,//first state
    text="",
    urlTree=[];
for(;;){
    curChar=url.charAt(0);//first char
    if(state===0){
        //expects http... ws... file or https, for example.
        if(curChar===""){
            throw new Error("http:// expected.")
        }else if(curChar===":"){
            if(directoryPassed){
                throw new Error("Unexpected token.")
            }
            urlTree.push({type:"URLProtocol",value:text});
            text="";
            state=1
        }else{
            text+=curChar
        }
    }else if(state===1){
        //expects //...
        if(url.substring(0,2)==="//"){
            state=2;
            url=url.substring(1)
        }else if(curChar===""){
            throw new Error("// expected.")
        }
    }else{
        //expects anything correct: site.com/dir, localhost:8080, ?get=0, etc.
        if(getStarted){
            if(curChar==="="){
                if(text.length===0){
                    throw new Error("Unexpected token.")
                }else{
                    expectGetValue=true;
                    getContent=""
                }
            }else if(curChar==="&"){
                if(expectGetValue||text.length!==0)
                    urlTree.push({type:"Variable",name:text,value: (getContent||true) });
                expectGetValue=false;
                text=""
            }else if(curChar===""){
                if(expectGetValue||text.length!==0)
                    urlTree.push({type:"Variable",name:text,value: (getContent||true) });
                break
            }else{
                if(expectGetValue){
                    getContent+=curChar
                }else{
                    text+=curChar
                }
            }
        }else if(curChar==="."){
            if(text.length===0){
                throw new Error("Unexpected token.")
            }else{
                if(inPort){
                    throw new Error("Unexpected token in port.")
                }else{
                    urlTree.push({type:"Name",value:text});
                    text=""
                }
            }
        }else if(curChar===""){
            if(text.length!==0){
                if(inPort){
                    urlTree.push({type:"Port",value:text})
                }else{
                    urlTree.push({type:"Name",value:text})
                }
                text=""
            }else if(inPort){
                throw new Error("Port not specified.")
            }
            break
        }else if(curChar==="?"){
            //$_GET starts here.
            if(text.length!==0){
                if(inPort){
                    urlTree.push({type:"Port",value:text})
                }else{
                    urlTree.push({type:"Name",value:text})
                }
                text=""
            }
            getStarted=true;
            urlTree.push({type:"Get"})
        }else if(curChar==="/"){
            if(text.length===0){
                throw new Error("Unexpected token.")
            }else{
                directoryPassed=true;
                if(inPort){
                    inPort=false;
                    urlTree.push({type:"Port",value:text})
                }else{
                    urlTree.push({type:"Name",value:text})
                }
                text="";
                urlTree.push({type:"NextDirectory"})
                //New directory!
            }
        }else if(curChar===":"){
if(portRead||text.length===0){
                throw new Error("Unexpected token.")
            }else{
                urlTree.push({type:"Text",value:text});
                text="";
                inPort=
                portRead=true;
                //Now the port will never be defined again.
            }
        }else if(inPort){
            if(/[0-9]/.test(curChar)){
                text+=curChar
            }else{
                throw new Error("Invalid port token.")
            }
        }else{
            text+=curChar
        }
    }
    url=url.substring(1)
}

一旦运行,你就会在url字符串中获得用base构造的urlTree数组。 另外,您的URL当前在数组中返回以下树:

解析

在代码中。 树数组中的每个项目都是一个对象。 每个对象都具有属性type type告诉项目代表什么。


在这个解析中,有这些类型(在字符串中 ):

"URLProtocol" - >它可能是http,https或其他任何东西。 具有属性: value (协议字符串,如:“http”,“ws”等)

"Name" - >这是某事的名字。 示例:name.name ... name.com ...?name = 0; 有属性: value (name string)

"NextDirectory" - >代表“/” - “打开一个新目录”

"Get" - >? 开始。 “现在可以声明URL变量”

"Variable" - >代表什么? 变量。 有属性: namevalue ;

基本。 就这样。 然后你可以用你自己的指令用数字循环解释数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM