简体   繁体   English

如何从URL获取值?

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

Asuming I have something like 假设我有类似的东西

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

How could I get the 24a34b83c72 ID using pure javascript? 如何使用纯javascript获取24a34b83c72 ID? I know that it's always after the questions/ part and that regardless if it contains a number or symbol, it needs to end before the next / . 我知道它总是在questions/部分之后,无论它是否包含数字或符号,它都需要在下一个/之前结束。 I tried things like; 我尝试过这样的事情;

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

But that resulted in the entire thread after it. 但这导致了整个线程。 I tried regular expresions but the closest I got to is: 我尝试了正常的表达,但我最接近的是:

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

Can anyone help me? 谁能帮我?

You could group everything after questions/ and before the next / , like so: 您可以在questions/之后questions/在下一个/之前对所有内容进行分组,如下所示:

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

You can see the output of url.match(..) is this: 你可以看到url.match(..)的输出是这样的:

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

The second item is there because of the parenthesis around [^/]+ , so you access it with url.match(..)[1] . 第二项是因为[^/]+周围的括号,所以你用url.match(..)[1]访问它。

Regular expressions are useful for more complex patterns, or repeated matches. 正则表达式对于更复杂的模式或重复匹配很有用。 Your requirements are simple and singular. 您的要求简单而单一。

Split the string by '/' , find the index of 'questions' , the result is in the next index: '/'拆分字符串,找到'questions'的索引,结果在下一个索引中:

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

If you insist in regexp: 如果你坚持regexp:

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

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

That should match the string provided as example. 这应该与作为示例提供的字符串匹配。

This worked for me, with your example on the Firefox console: 这对我有用,你的示例在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" ]

The second element of the array should be what you are looking for. 数组的第二个元素应该是您正在寻找的。

[Another option] [另外一个选项]

I'd interpret the URL string first and after interpret what the interpretation returns for me ( as a Abtract syntax tree ). 我首先解释URL字符串,然后解释解释为我返回的内容( 作为 Abtract语法树 )。 The following commands block will eat the url string while the below loop is executing (or interpreting ), constructing a representative array in steps! 以下命令块将在下面的循环执行(或解释 )时使用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)
}

Once it's ran, you get the urlTree array constructed with base in the url string. 一旦运行,你就会在url字符串中获得用base构造的urlTree数组。 Additionaly, your URL currently returns the following tree in a array: 另外,您的URL当前在数组中返回以下树:

解析

in the code. 在代码中。 Every item from tree array is a object. 树数组中的每个项目都是一个对象。 Every object has the property type . 每个对象都具有属性type type tolds what the item represents. type告诉项目代表什么。


In this parsing, there are these types (in string ): 在这个解析中,有这些类型(在字符串中 ):

"URLProtocol" -> It maybe http, https or anything else. "URLProtocol" - >它可能是http,https或其他任何东西。 Has the property: value (protocol string, as: "http", "ws", etc) 具有属性: value (协议字符串,如:“http”,“ws”等)

"Name" -> It's name of something. "Name" - >这是某事的名字。 Example: name.name... name.com... ?name=0; 示例:name.name ... name.com ...?name = 0; Has the property: value (name string) 有属性: value (name string)

"NextDirectory" -> Represents "/" - "A new directory opened" "NextDirectory" - >代表“/” - “打开一个新目录”

"Get" - > ? "Get" - >? started. 开始。 "Now URL variables maybe declared" “现在可以声明URL变量”

"Variable" -> represents ? "Variable" - >代表什么? variable. 变量。 Has the properties: name and value ; 有属性: namevalue ;

Basic. 基本。 That's all. 就这样。 Then you may interpret the array with a numeric loop with your own instructions. 然后你可以用你自己的指令用数字循环解释数组。

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

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