Say I have a URL like this:
www.mysite.com?account=23&token=asdu756sdg65sdf
Now, I need to access those URL parameters individually using Angular JS.
I've tried using location.search inside my controller:
console.log(location.search);
Which nicely returns the full query string:
?account=23&token=asdu756sdg65sdf
But it seems to return a string, not an object. Is there an easy way to access the individual ids and values in the string?
I've also tried:
console.log($location.search());
Which seems to return an empty object.
Try with
var account = ($location.search()).account;
but the url should be like /#!/?account=1
have your tried using it as a function instead?
$location.search();
pure js way:
var getParamFromURL = function(_url) {
var url = _url;
var _paraString = url.indexOf("&") > -1 ? url.substring(url.indexOf("?") + 1, url.length).split("&") : url.substring(url.indexOf("?") + 1, url.length).split('');
var _paraObj = {};
for (i = 0; p = _paraString[i]; i++) {
_paraObj[p.substring(0, p.indexOf("=")).toLowerCase()] = p.substring(p.indexOf("=") + 1, p.length);
}
return _paraObj;
}
via angular js:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
Great. #Cooper is right.
Related
Consider I have following JSON object
var urls = {
"GET/users/:id":1,
"POST/users":0
}
and if I have string "GET/users/10". How can I use this as key to get the value from urls JSON i.e. "GET/users/10" should match "GET/users/:id".
I don't want to iterate urls JSON and use regex for every key.
Is there a way to access JSON object using regex?
Thanks in advance.
Here is something that should work for you. I took some of the pieces from the Durandal router's RegEx matching logic which basically dynamically creates a regular expression object based on a defined route string and then tests with it against a passed string.
Here is the working example:
var urls = {
"GET/users/:id": 1,
"POST/users": 0
}
const getRouteRegExp = (
routeString,
routesAreCaseSensitive = false,
optionalParam = /\((.*?)\)/g,
namedParam = /(\(\?)?:\w+/g,
splatParam = /\*\w+/g,
escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g
) => {
routeString = routeString.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\/]+)';
})
.replace(splatParam, '(.*?)');
return new RegExp('^' + routeString + '$', routesAreCaseSensitive ? undefined : 'i');
}
const getRouteByString = (string) => {
var resultArr = Object.entries(urls).find(([k, v]) => {
var regEx = getRouteRegExp(k)
return regEx.test(string)
}) || []
return resultArr[0]
}
console.log(getRouteByString('GET/users/10'))
console.log(getRouteByString('POST/users'))
console.log(getRouteByString('POST/users2'))
So what you have is the getRouteRegExp function which is the main thing here which would compose a regular expression object based on a passed route.
After that we go and for each existing route defined in urls we create one RegExp and try to match it against the provided string route. This is what the find does. If one is found we return it.
Since we are doing Object.entries we return the 0 index which contains the result.
Since this comes straight from the Durandal bits it supports all the route expressions that are built in Durandal ... like:
Static route: tickets
Parameterized: tickets/:id
Optional Parameter: users(/:id)
Splat Route: settings*details
You can read more about Durandal Router here
From your question what I can understand is your key is dynamic, so you can do something like this:
var urls = {
"GET/users/:id":1,
"POST/users":0
}
let id = 10
const yourValue = urls["GET/users/" + id]
You can use this code to
var urls = {
"GET/users/:id":1,
"POST/users":0
}
var regex = /"([^"]+?)"\s*/g;
var urlsJson = JSON.stringify(urls);
let result = regex.exec(urlsJson)
if(result && result.length > 0) {
var keyJson = result[1];
var value = urls[keyJson]
console.log('value', value)
}
Try Something like this:
const urls = (id) => ({
[`GET/users/${id}`]:1,
"POST/users":0,
});
console.log(urls(2));
I hope it may be helpful.
The json would look fine, just do a replace on the url, so replace the ending integer with :id and then you have the key by which you can directly access the value in the json.
So:
var url = "GET/users/10";
var urls = {
"GET/users/:id":1,
"POST/users":0
}
url = url.replace(/users\/\d+/, 'users/:id');
console.log(urls[url]);
Do as many replaces on the url to convert all possible url's to the keys in your json.
We want to remove multiple query string parameters from given url. For example:
If url is:
https://www.example.com?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1
and
if query string parameters to be removed are: "so","kms","pn", the output of that function should be:
https://www.example.com?budget=0-&year=0-&sc=-1
We have written following code for this:
var input = "https://www.example.com?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1";
var url = input.replace('?', '');
var removeFilterSet = {"so" : true,"kms" : true,"pn" : true};
var params = url.split("&");
for(var i = params.length ; i-- > 0 ; )
{
if(removeFilterSet[params[i].split("=")[0]])
{
params.splice(i,1);
}
}
alert(params.join("&"));
Is there any better way to remove query string in bulk from url?
One could use a Map for that:
const url = "https://www.example.com?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1";
//divide the url into domain and query
const [domain,query] = url.split("?");
//build a Map out of the query string
const params = new Map(
query.split("&").map(el=>el.split("="))
);
//modification goes here, e.g:
["year","so","sc","pm"].forEach(q => params.delete(q));
/* or to replace a value
params.set("whatever","value")
*/
//build up again:
const result = domain+"?"+[...params].map(el=>el.join("=")).join("&");
Try it
You can use this code that use the most of the split() function to achieve the desired goal:
var input = "https://www.example.com?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1";
var domain = input.split("?")[0];
var queryStrings = input.split("?")[1].split('&');
var removeFilterSet = {"so" : true,"kms" : true,"pn" : true};
var resArray = [];
queryStrings.forEach(function(value, key){
var queryName = value.split('=')[0];
if(!removeFilterSet[queryName]){
resArray.push(value);
}
});
var finalUrl = domain+'?'+resArray.toString().replace(/,/g,'&');
console.log(finalUrl);
Here a solution using Array.prototype.reduce():
let input = "https://www.example.com?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1",
[domain, qs] = input.split('?'),
removeFilterSet = ['so', 'kms', 'pn'],
filtered = qs.split('&').reduce((acc, param) => {
return removeFilterSet.includes(param.split('=')[0]) ?
acc : `${acc}&${param}`;
}, '');
console.log(domain + '?' + filtered);
Yes - use a library rather than try and do anything complicated. I recommend URIJS, which does it like this:
var uri = new URI("https://www.example.com?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1");
uri.removeSearch(["so", "kms", "pn"]);
alert( uri.toString() );
See https://medialize.github.io/URI.js/docs.html#search-remove for details.
Old post but here's my cleaner solution. I'm utilizing the lodash and query-string libraries.
import qs from "query-string";
import _ from "lodash";
let query = qs.parse(location.search);
_.map(query, function(value, key) {
return delete query[key];
});
I try to test the function s.Util.getQueryParam.
The url I have is in format
http://project1/project1.html
I would like to add some parameters in the url after that in order to have something like this format
http://project1/project1.html/?id=03
I try to use this example
// www.mysite.com/my_app.html?Use_Id=abc
var GET = {};
var query = window.location.search.substring(1).split("&");
for (var i = 0, max = query.length; i < max; i++)
{
if (query[i] === "") // check for trailing & with no param
continue;
var param = query[i].split("=");
GET[decodeURIComponent(param[0])] = decodeURIComponent(param[1] || "");
}
I try to add in Get this id=03 but it is not working when I refresh my browser I can't see the parameter. Is it possible to help me how can I run it with the right way?
You can modify window.location.search to add query parameters. This will cause the browser to load the new URL (the page will be refreshed).
Example: window.location.search = '?id=03'.
I'm currently building a URL string from form inputs to look something similar to this:
api/search/127879/11-28-2013/7/2/undefined/undefined/undefined/LGW/null
How would i find any or all variables that === to undefined and then remove from these from the string above?
if you dont want to chage logic of building url than just make use of replace function of javascript
var str = "api/search/127879/11-28-2013/7/2/undefined/undefined/undefined/LGW/null";
var res = str.replace(/undefined\//gi,"");
If you are generating string yourself, then check before appending it to urlString.
If you get the string from server, then do this:
var finalUrl = "";
var urlStr= "api/search/127879/11-28-2013/7/2/undefined/undefined/undefined/LGW/null";
var urlArray = urlStr.split('/');
for (i = 0, i = urlArray.length; i ++) {
if(urlArray[i] === undefined)
{
//do nothing
}
else
{
finalUrl += urlArray[i];
}
}
Hope this helps.
Say I have http://www.mysite.com/index.php?=332
Is it possible to retrieve the string after ?= using jQuery? I've been looking around Google only to find a lot of Ajax and URL vars information which doesn't seem to give me any idea.
if (url.indexOf("?=") > 0) {
alert('do this');
}
window.location is your friend
Specifically window.location.search
First your query string is not correct, then you can simply take the substring between the indexOf '?=' + 1 and the length of the string. Please see : http://www.w3schools.com/jsref/jsref_substring.asp
When it is easy to do without JQuery, do it with js only.
here is a code snippet (not by me , don't remember the source) for returning a value from a query string by providing a name
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results)
{ return 0; }
return results[1] || 0;
}
var myArgs = window.location.search.slice(1)
var args = myArgs.split("&") // splits on the & if that's what you need
var params = {}
var temp = []
for (var i = 0; i < args.length; i++) {
temp = args[i].split("=")
params[temp[0]] = temp[1]
}
// var url = "http://abc.com?a=b&c=d"
// params now might look like this:
// {
// a: "a",
// c: "d"
// }
What are you trying to do? You very well may be doing it wrong if you're reading the URL.