Regex for url line [duplicate] - javascript

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.

Related

Get values of parameters from URL

I’m working on a tool which takes the value parameters in the URL and does a few things with them.
My issue is, I can’t seem to use document.location to show the specific value that I’m after, for example:
www.examplesite.com?yourname=gilgilad
I want to use document.location.search and put it in a var, I need that var's value to be "gilgilad".
Is this even possible using location.search?
location.search will return all after question mark including it. So there is universal js to get value of the first parameter (even if url has more parameters):
var desire = location.search.slice(1).split("&")[0].split("=")[1]
Example: let's take url http://example.com?name=jon&country=us
location.search will be equal to ?name=jon&country=us
.slice(1) skips the ?, returning the rest of the string.
.split("&")[0] splits it into two strings (name=jon and
country=us) and takes first one
.split("=")[1] splits name=jon into name and jon and takes the second one. Done!
let url = new URL('www.examplesite.com?yourname=gilgilad');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('yourname'));
you can consider also to user window.location or window.location.search directly
let searchParams = new URLSearchParams(window.location.search);
console.log(searchParams.get('yourname'));
A more generic solution to split the location.search query parameters and convert them into an object:
var a = location.search.split("&");
var o = a.reduce(function(o, v) {
var kv = v.split("=");
kv[0] = kv[0].replace("?", "");
o[kv[0]] = kv[1];
return o;
},
{});
To make ?yourname=gilgilad using document.location.search:
window.location.search = 'yourname=gilgilad';
here is jsfiddle: http://jsfiddle.net/t81k3bgc/
make sure to use console and then [run]. you will see:
For more information:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location#Example_.235.3A_Send_a_string_of_data_to_the_server_by_modifying_the_search_property.3A

Passing in a key results in extra characters in my firebase URL, how do I remove them?

When placing the "key" variable inside of this string, it displays 'simplelogin%3A5' instead of 'simplelogin:5'. Is there a way to just pass in the latter?
var populateTasks = function(date, key){
$scope.ref = new Firebase("https://myfirebase.firebaseio.com/users/"+key+"/tasks");
};
results in: https://myfirebase.firebaseio.com/users/simplelogin%3A5/tasks
I need: https://myfirebase.firebaseio.com/users/simplelogin:5/tasks
var uri = "//what you need to convert";
var uri_dec = decodeURIComponent(uri);
var res = uri_dec;
Where does the value of key come from? If you get it from a URL, it makes sense that you see %3A.
A : has a special meaning in a URL, so it is escaped. And the URL escape sequence for a : is %3A.
To convert the %3A back to : you simply unescape it like this:
unescape(key)
Or use decodeURIComponent, which in this case accomplishes the same. The best way to decode the value depends on why it was encoded in the first place, hence my initial question.
Have you tried trimming key before concatenating it to the URL?
key = key.trim();

jQuery regex match returning empty string

I need to strip out the IDs of embedded youtube videos, so I have the url which is something like:
www.youtube.com/embed/[someID]&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1
All I want is the [someID] string. I have declared an empty array to store the regex matches;
var videoID = [];
The closest I have come to a solution is:
videoID = videoID.match("embed/(\w*)");
but this results in the following:
video[0] ("embed/")
video[1] ()
Use this:
url = "www.youtube.com/embed/someID&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1";
Then use either:
var videoID = url.match(/embed\/(\w*)/); // regex
OR else:
var videoID = url.match("embed/\\w*)"); // regex object
Both will give this output:
["embed/someID", "someID"]
If you provide a string then String#match method will attempt to construct a RegExp object and for that case you need to use \\w instead of \w.
Try this you may get id. I didn't use regex but still we can get id from above demo like urls.
var url ="www.youtube.com/embed/[someID]&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1";
var urlQueries = url.split('/');
var queryParameters = urlQueries[2].split('&'); // arrays of all query parameters
var id = queryParameters[0]; // get ids at index 0
Working demo here
I'm not sure if jquery can do Positive-Lookbehinds, but try this (?<=embed\/)([^&]*)
If not, then (?:embed\/)([^&]*) is closer to your example.
Demo:
http://regex101.com/r/nW5uL8

parse url to get id using javascript regex

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.

Using javascript regex to translate a html

I would like to build my own translation function in javascript.
I already have a function language.lookup(key) which translates a word or expression:
var frenchHello = language.lookup('hello') //'bonjour'
Now I would like to write a function which takes a html string and translates it with my lookup function. In the html string I will have a special syntax for example #[translationkey] that will point out that this word should be translated.
This is the result I want:
var html = '<div><span>#[hello]</span><span>#[sir]</span>'
language.translate(html) //'<div><span>bonjour</span><span>monsieur</span>
How would I write language.translate?
My idea is to filter out my special syntax with regex and then run language.lookup on each key. Maybe with string replace or something.
I suck when it comes to regex and I've only come up with a very incomplete example but I include it anyway so maybe someone get the idea of what I am trying to do. Then if there is a better but complete different solution that is more than welcome.
var value = "#[hello], nice to see you.";
lookup = function(word){
return "bonjour";
};
var res = new RegExp( "\\b(hello)\\b", "gi" ).exec(value)
for (var c1 = 0; c1 < res.length; c1++){
value = value.replace(res[c1], lookup(res[c1]))
}
alert(value) //#[bonjour], nice to see you.
The regex should of course not filter out the word hello but the syntax and then collect the key by grouping or similar.
Can anyone help?
Just use String.replace method's ability to call function specified as second argument to generate replacement text and make a global replace using regexp matching your syntax:
var value = "#[hello], #[sir], nice to see you.";
lookup = function(full_match, word){
if(word == 'hello')
return "bonjour";
if(word == 'sir')
return "monsieur"
};
console.log(value.replace(/#\[(.+?)\]/gi, lookup))
Result:
bonjour, monsieur, nice to see you.
Of course when your replacement list gets bigger, you'd better use lookup object instead of series of ifs in lookup function, but you can really do whatever you want there.
You can try this to find all occurrences:
var re = new RegExp('#\\[([^\\]]+?)\\]', 'gi'),
str = '#[value1] plain text #[value2]',
match;
while (match = re.exec(str)) {
console.log(match);
}
You could use something like:
#\\[[^\\]]*\\]
Which matches the hash followed by an opening square bracket followed by zero or more characters NOT including the closing square bracket, followed by a closed square bracket.
Alternatively, perhaps it would be better to handle the translation at the server side (maybe even through your template engine) and send back to your client the translated response. Otherwise, (depending on the specific problem you are dealing with of course), you might end up sending a lot of data to the browser which might make your application respond slowly.
EDIT:
Here is a working piece of code:
var q="This #[ANIMAL1] was eaten by that #[ANIMAL2]";
var u = {"#[ANIMAL1]":"Lion","#[ANIMAL2]":"Frog"};
function insertAnimal(aString, lookup){
var res = (new RegExp("#\\[[^\\]]*\\]", "gi"))
while (m = res.exec(aString)){
aString = aString.replace(m, lookup[m])
}
return aString;
}
function main(){
alert(insertAnimal(q,u));
}
You can call the "main()" from an HTML document's body onload event
I can compare your requirement to 'resolving template texts within content'. If it is feasible to use Jquery , you should try Handlebars.js
.

Categories