I am writing a router which will parse the url and redirect to necessary components in the code, when I change my url and pass object id with it, I want to parse it using regular expression and route it to get that object by id.
mysite.com/blah#path=folder/?folderId=klafjlka
How do I parse this url using javscript regex and route it to that folder
With reference to backbone, I want to write a code which does this, but I'm not using backbone
routes : { "folder/:id" : "handler" },
I tend to find that using .split normally creates much more readable code in these situations.
If you use window.location.hash to get your data originally, you'll be left with
#path=folder/?folderId=klafjlka
Eliminating the first lot of un-needed stuff. The rest can be simply done with a split and a looped split.
//Remove the initial hash from the window.location.hash
var hash = window.location.hash.substr(1),
//Split it down so we have ["path=folder","folderId=klafjlka"]
paramSplit = hash.split("/?");
var params = {};
for (var x=0; x<paramSplit.length; x++){
//Split it at the equals
var split = paramSplit[x].split("=");
params[split[0]]=split[1];
}
console.log(params);
Params should return
{
path: "folder",
folderId: "klafjlka"
}
Which is easy to use for whatever your purposes are.
If your url is in a string and has always the same structure
var url = 'mysite.com/blah#path=folder/?folderId=klafjlka';
var re = /#path=(.+?)\?folderId=(.*)/i
var args = url.match(re);
var path = args[1];
var id = args[2];
this searches for #path= and captures the following characters until ? and then searches for ?folderId= and captures everything else.
Now path will contain folder/ and id wil contain klafjlka.
Related
This should be very simple (when you know the answer). From this question
I want to give the posted solution a try. My question is:
How to get the parameter value of a given URL using JavaScript regular expressions?
I have:
http://www.youtube.com/watch?v=Ahg6qcgoay4
I need:
Ahg6qcgoay4
I tried:
http://www.youtube.com/watch\\?v=(w{11})
But: I suck...
You almost had it, just need to escape special regex chars:
regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;
url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'
Edit: Fix for regex by soupagain.
Why dont you take the string and split it
Example on the url
var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"
you can do a split as
var params = url.split("?")[1].split("&");
You will get array of strings with params as name value pairs with "=" as the delimiter.
Not tested but this should work:
/\?v=([a-z0-9\-]+)\&?/i
v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk
In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString
HttpUtility.ParseQueryString(url)["v"];
And you don't even need to check the key, as it will return null if the key is not in the collection.
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
DEMO
I use seperate custom functions which gets all URL Parameters and URL parts .
For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The above function will return an array consisting of url variables.
For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b
I use a simple uri split,
function getUrlParams() {
var vars = {};
var parts = window.location.href.split('/' );
return parts;
}
You can even combine them both to be able to use with a single call in a page or in javascript.
I have this link/string:
https://link/to/a/file/filename.ext
My JS skills are now rusty and I need to trim the link from the last instance of / so that I could separate the directory and the file name (with the file extension attached to the file name).
var string = 'https://link/to/a/file/filename.ext';
var directory = 'https://link/to/a/file/'; // should have a value of 'https://link/to/a/file' coming from var string
var file = 'filename.ext'; // should have a value of 'filename.ext' coming from var string
You can use split() and join()
var string = 'https://link/to/a/file/filename.ext';
const strArray = string.split('/');
var file = strArray.pop();;
var directory = strArray.join('/');
console.log(file, directory);
var string = 'https://link/to/a/file/filename.ext';
directory = string.substring(0, string.lastIndexOf("/"));
console.log(directory);
file = string.substr(string.lastIndexOf("/")+1);
console.log(file);
/ In the search parameters
The other solutions split the whole url at the last /, but in practice you can have situations where the search parameters contain a /. For example, a redirect parameter for a single sign on.
The example below uses the URL object to parse the URL first so that you don't have to mess with that, then uses just the path name to get the parts you want:
//Based on a real SSO url
var u = new URL('https://idp.blarg.edu/made/up/url/file.ext?service=https://some.webservice.blarg.edu/some/thing/on/the/internet.net?FolderPath=thingy.CO_EMPLOYEE_SELF_SERVICE.BLARG%26IsFolder=false%26IgnoreParamTempl=FolderPath%2cIsFolder%26');
// Split the path only on the last /, (no url params)
// I like a regex here cause it splits exactly into 2, but split() may be more readable...
[_, path, file] = u.pathname.match('^(.*)/([^/]*)$');
console.log(u.origin + path);
console.log(file);
I am using a regular expression to capture a URL string, but it's not working out.
Here's my code, which is coming from an external JavaScript document, linked to the HTML file:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch);
The output that I get is this: "www.google.com,www.,,www."
What am I doing wrong?
Thanks! :)
Your regex works fine, what happens is that according to the match function you are getting one extra result for each group (defined by these parenthesis) that you have in your regex. to access the whole match you can access to the first item of the match return like the following:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx)[0]; //this line changed, im using [0] to access the whole match only
document.write(urlRegMatch);
working example: https://jsfiddle.net/2sptg5rz/3/
reference about the match function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Return_value
I'd like to thank #Dknacht and #Tressa for directing me to the correct answer, since the first value of the array, 0, is the matched text.
This code works for what I want to do:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch[0]);
From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)
I have following url's and all these url are considered root of the website, how can I use javascript location.pathname using regex to determine pattern below, as you'll notice the word "site" is repeating in this pattern..
http://www.somehost.tv/sitedev/
http://www.somehost.tv/sitetest/
http://www.somehost.tv/site/
http://www.somehost.tv/sitedev/index.html
http://www.somehost.tv/sitetest/index.html
http://www.somehost.tv/site/index.html
I am attempting to display jQuery dialog only and only if the user is at the root of the website.
Simply use the DOM to parse this. No need to invoke a regex parser.
var url = 'http://www.somesite.tv/foobar/host/site';
urlLocation = document.createElement('a');
urlLocation.href = url;
alert(urlLocation.hostname); // alerts 'www.somesite.tv'
A complete pattern, including protocol and domain, could be like this:
/^http:\/\/www\.somehost\.tv\/site(test|dev)?\/(index\.html)?$/
but, if you're matching against location.pathname just try
/^\/site(test|dev)?\/(index\.html)?$/.test(location.pathname)
If you do not explicitly need a Regular Expression for this
You also could do for example
Fill an array with your urls
Loop over a decreasing substring of
the shortest element.
Comparing it against
the longest element.
Until they match.
var urls = ["http://www.somehost.tv/sitedev/",
"http://www.somehost.tv/sitetest/",
"http://www.somehost.tv/site/",
"http://www.somehost.tv/sitedev/index.html",
"http://www.somehost.tv/sitetest/index.html",
"http://www.somehost.tv/site/index.html"]
function getRepeatedSub(arr) {
var srt = arr.concat().sort();
var a = srt[0];
var b = srt.pop();
var s = a.length;
while (!~b.indexOf(a.substr(0, s))) {
s--
};
return a.substr(0, s);
}
console.log(getRepeatedSub(urls)); //http://www.somehost.tv/site
Heres an example on JSBin