简体   繁体   中英

How to get values from a URL using hash and split

I have a url like this

http://localhost:9000/index.html#/acceptRequest?screen_name=kailash&rf=FIN1

Here I want to take FIN1 from the url and store it in another variable I am using doing this in angularjs

I have made a function like this

function getUrlVars()
{ 
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
        console.log(hash[1]);
    }
    return vars;
}

Here the console line hash[1] prints kailash FIN1.I only need the FIN1 to be stored and just print it in the console.How to make that happen?... Anyway thanks in advance...

If the URL is for a resource in your Angular app, you can simply inject the $location service and use

var anotherVariable = $location.search().rf

See https://docs.angularjs.org/api/ng/service/$location#search

This code will get the url parameter you need. You just have to call it and tell what value you need.

function getUrlParameter(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    } else {
        return results[1] || 0;
    }
};

Use it like

var yourVariable= getUrlParameter("rf");

It will return the value of rf.

Hope this helps.

Here is simple solution for you.In core Javascript .

 var url = "http://localhost:9000/index.html#/acceptRequestscreen_name=kailash&rf=FIN1"; var test = url.lastIndexOf('='); var r = url.slice(test+1); alert(r); 

After some research i got an answer

we just have to store the return value of that function to a variable like this

var urlParams = getUrlVars();

then all we need to do is to

console.log(urlParams['rf']);

thats it...

anyway you guys have been a great help... Thank you for responding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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