JavaScript: How to Strip out everything and just get the ID? - javascript

I'm creating a Bookmarklet for YouTube, i want to get the ID from the youtube link,
Ex: http://www.youtube.com/watch?v=YgFyi74DVjc
I want only "YgFyi74DVjc" from the above link, that's just an example of what i want, it has to strip out everything and just leave that end part, another thing is
i want to get the ID from this URL as well
http://www.youtube.com/verify_age?next_url=http%3A//www.youtube.com/watch%3Fv%3D[YOUTUBEID]
So basically when you click on some video and then on this bookmarklet it gets the youtube video ID and redirects them to a link which unlocks the video or expands the video to full size of the user's browser, i have everything coded and just need a way to get ID's from both the links, i have coded this which works for the 2nd link
var url = "http://www.youtube.com/verify_age?next_url=http%3A//www.youtube.com/watch%3Fv%3D[YOUTUBEID]";
var ytcode = url.substr(80,50);
alert(ytcode);
Now i want someway to get ID's from both the links, please help!

This is a job for regex:
url.match(/(\?|&)v=([^&]+)/).pop()
which, broken down, means:
url.match(
// look for "v=", preceded by either a "?" or a "&",
// and get the rest of the string until you hit the
// end or an "&"
/(\?|&)v=([^&]+)/
)
// that gives you an array like ["?v=YgFyi74DVjc", "?", "YgFyi74DVjc"];
// take the last element
.pop()
You can use this for the second form as well if you decode it first:
url = decodeURIComponent(url);
The url variable now equals "http://www.youtube.com/verify_age?next_url=http://www.youtube.com/watch?v=[YOUTUBEID]", and the regex should work.
You could put it all together in a reusable function:
function getYouTubeID(url) {
return decodeURIComponent(url)
.match(/(\?|&)v=([^&]+)/)
.pop();
}

Assuming the ID (i.e. the v parameter) is always the last parameter in the URL:
url = url.replace("%3D", "=");
var splitUrl = url.split("=");
var yId = splitUrl[splitUrl.length - 1];
The replace function is used to replace the character code %3D with =, which is what it represents. You can then split the string on the = character, and your ID will be the last element in the resulting array.

You could use this function (just pass it the url and the name of the parameter)
function getParameterByName( name, url )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var url = "http://www.youtube.com/watch?v=YgFyi74DVjc"
var v= getParameterByName('v', url);

Slight modification to nrabinowitz answer to allow for YouTube share URLs such as:
http://youtu.be/3Ah8EwyeUho
Also i have attached it to a class so it can be easily reused.
$(function(){
$('.js-youtube').on('blur', function(){
var newval = '';
if (newval = $(this).val().match(/(\?|&)v=([^&#]+)/)) {
$(this).val(newval.pop());
} else if (newval = $(this).val().match(/(youtu\.be\/)+([^\/]+)/)) {
$(this).val(newval.pop());
}
});
});

Related

Find and replace a string with a number attached

Sample URL:
.com/projects.php?&filterDate=this_week?page=5
The query strings like I've listed above may or may not have the ?page=5 query string in them. I'm looking for a way to grab the URL (done), search the string to determine whether or not it has the ?page=# query string (also done), add it in if it's not there (also done), but if it is there, replace it with a different number (need help with this). The code currently doesn't change the query string (ie page=5 doesn't change to page=6 or anything else for that matter). It doesn't seem like the .replace method's regex is correct (see current_window_location3 variable) below.
//Get the current URL
var current_window_location = window.location.href;
if(current_window_location.match("\\?page=([^&]+)")){
//Replace this query string
var current_window_location3 = current_window_location.replace("\\?page=([^&]+)", new_page_num);
//Go to this newly replaced location
window.location = current_window_location3;
}else{
//Add clicked '?page=#' query string to the URL
var current_window_location2 = current_window_location + "?page="+new_page_num;
//Go to this new location
window.location = current_window_location2;
}
String.prototype.replace() takes as its first value, the search pattern, a string or a regex. If a string ("abc?") is given, it searches for the literal string to replace. If a regex (/abc?/) is passed a regex match, a search is done using regular expressions.
Change your
var current_window_location3 = current_window_location.replace("\\?page=([^&]+)", new_page_num);
to
var current_window_location3 = current_window_location.replace(/\?page=([^&]+)/, new_page_num);
Here's an illustrating snippet:
var current_window_location = '.com/projects.php?&filterDate=this_week*?page=5*',
window_location = '',
new_page_num = 123;
if(current_window_location.match("\\?page=([^&]+)")){
//Replace this query string
var current_window_location = current_window_location.replace(/\?page=([^&]+)/, new_page_num);
//Go to this newly replaced location
window_location = current_window_location;
} else {
//Add clicked '?page=#' query string to the URL
var current_window_location = current_window_location + "?page="+new_page_num;
//Go to this new location
window_location = current_window_location;
}
document.write("window_location = " + window_location);

regex: get string in url login/test

I have a url
https://test.com/login/param2
how do I get the the second parameter "param2" from the url using REGEX?
the url can also be
https://test.com/login/param2/
So the regex should work for both urls.
I tried
var loc = window.location.href;
var locParts = loc.split('/');
and then looping through locParts, but that seems inefficient.
The "param2" can be have number, alphatical character from a-z, and a dash.
Use String#match method with regex /[^\/]+(?=\/?$)/.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var reg = /[^\/]+(?=\/?$)/;
console.log(
a.match(reg)[0],
b.match(reg)[0]
)
Or using String#split get last non-empty element.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var splita = a.split('/'),
splitb = b.split('/');
console.log(
splita.pop() || splita.pop(),
splitb.pop() || splitb.pop()
)
If you don't mind using JS only (so no regex), you can use this :
var lastParameter = window.location.href.split('/').slice(-1);
Basicaly, like you, I fetch the URL, split by the / character, but then I use the splice function to get teh last element of the split result array.
Regular expressions might be compact, but they're certainly not automatically efficient if you can do what you want without.
Here's how you can change your code:
var loc = 'https://test.com/login/facebook/'; // window.location.href;
var locParts = loc.split('/').filter(function(str) {return !!str});
var faceBookText = locParts.pop();
console.log(faceBookText);
The filter removes the last empty item you would get if the url ends with '/'. That's all you need, then just take the last item.

Check if URL has anything after second "/" using javascript / jquery

So I have a completely variable url:
www.whatever.com/something/pagename
I need something to happen on the homepage of the websites and not on any of the other pages. Sometimes the homepage has a "something" in the url and sometimes it doesn't, so I need to find out if "pagename" exists, whatever it may be.
all values in the url vary so i can't simply search for a string in the url..
Is this possible to do this using only JS / JQuery?
Thanks
Split is the solution:
var exampleURL = "www.whatever.com/something/pagename";
var pageName = exampleURL.split("/")[2];
console.log(pageName);
//OUT -> pagename
Split the URL and then check the length of the result.
var split_url = url.split('/');
if (split_url.length > 2) {
// URL is like www.whatever.com/something/pagename...
} else {
// URL is just www.whatever.com or www.whatever.com/something
}
Another way is with a regular expression that matches a URL with two slashes:
if (url.match(/\/.*\//)) {
// URL contains two slashes
} else {
// URL has at most one slash
}
You could do a regex check:
/^[^\/\s]*(\/\/)?[^\/\s]+\/[^\/\s]+[^\/]+\/[^\/\s]+$/.test('www.whatever.com/something/pagename')
demo:
https://regex101.com/r/vF1bH8/1
The question is not really clear, but to answer the title literally https://jsfiddle.net/jgfeymk1/
function after2ndFSlash(inpu){
var pieces = inpu.split('/');
var output = document.getElementById('output');
if(pieces.length>2){
output.innerHTML += 'true<br/>';
}
else{
output.innerHTML += 'false<br/>';
}
}
Assuming that url string has protocol included ... http(s):// ... you can pass it to href of an <a> element and access the pathname property
var url ='http://www.whatever.com/something/pagename'
var a = document.createElement('a');
a.href = url;
var pathParts = a.pathname.replace(/^\//,'').split('/');//["something","pagename"]
alert(pathParts[1]); //"pagename"

Javascript parse id from referrer

I am using the document.referrer property to get the following URLs:
http://www.site.ru/profile/521590819123/friends
http://www.site.ru/profile/521590819123
http://www.site.ru/profile/521590819123/else
I need to get the ID (for instance, 521590819123 as seen above) from this string into a variable. Here is what I have so far:
<script type="text/javascript">
var ref = document.referrer;
var url = 'http://site.com/?id=';
if( ref.indexOf('profile') >= 0 )
{
ref = ref.substr(ref.lastIndexOf('/') + 1);
window.top.location.href = (url+ref);
}
else
{
window.top.location.href = (url + '22');
}
</script>
But this only works if the referrer string is in the format http://www.site.ru/profile/521590819123. The other examples above with /friends or /else on the end won't work. Can someone help me fix the code to take care of these instances?
Easiest with a regex:
var m, id;
m = /profile\/(\d+)/.exec(document.referrer);
if (m) {
id = m[1];
}
That regex says "Find the first location where the text profile/ is followed by digits and put the digits in a capture group." Then the code checks that there was a match (in case the string doesn't have it at all) and, if so, takes the value from the first capture group (which is at index 1; index 0 is the whole matching string). Modify as necessary (for instance, to only match if the string is www.site.ru/profile/ rather than just profile/, etc.).

Regex for parsing parameters from url

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/

Categories

Resources