I'm trying to find a way to get a url from an iframe and using javascript modify the link and move to a another page. basicly the address in the iframe is something like "http://www.somthing.com/12/somt/arr_1.htm", using the javascript I want to remove the last five character (leaving this "http://www.somthing.com/12/somt/arr_") and than add the next logical number to it (making the link this "http://www.somthing.com/12/somt/arr__2.htm").
So far I have something like this.
<script language="javascript" type="text/javascript">
function urlGen(f){
var i1 = document.getElementById("iframe_id").contentWindow.location.href;
var i2 = "1.htm";
var i3 = "2.htm";
var newURL = i1 - i2 + i3
f.action = i1 - i2 + i3
return i1 - i2 + i3;
}
</script>
So based on what I understand from what you said it should look something like this?
so it should look something like this? (keep in mind I'm the forest gump of javascript... "I'm not a smart man but I know what java is")
<script language="javascript" type="text/javascript">
function urlGen(f){
var i1 = document.getElementById("iframe_id").contentWindow.location.href = newURL;
newURL = il.slice(0, -5);
var i3 = "2.htm";
f.action = newURL + i3
}
</script>
Try with this regular expression match
var i1 = "http://www.somthing.com/12/somt/arr_41.htm";
s = i1.replace(/\d+\.htm$/, function(attr) {
return attr.replace(/\d+/, function(val) {
return parseInt(val,10) + 1;
});
});
alert(s);
This will change any string that ends in X.htm (where X is a digit) in the same string with X+1 in place of X (adapted from https://stackoverflow.com/a/1742841).
You are grabbing the url correctly however your string manipulation isn't going to work.
You have a special function for trimming the string:
newUrl = i1.slice(0, -5);
This will trim the last 5 characters of the url.
newUrl = newUrl + i3;
This will concat the modified url with the new one.
return newUrl;
now when you do:
document.getElementById("iframe_id").contentWindow.location.href = newUrl;
It will use the new url.
With working example:
This example also incorporates the number addition:
i1.substr(0,i1.lastIndexOf("_")+1);
This bit uses the string function substr. It is used to retrieve part of a string. The first parameter is the start location, while the second marks the end. I use the string function lastIndexOf to find the location of the last used underscore in the url, then add one to make sure it includes the underscore. The code line above will print:
http://stacksnippets.net/arr_
To build the new url, we need to now the number. parseInt helps ur here:
(parseInt(i1.substr(i1.lastIndexOf("_")+1), 10)+1)
I've put the entire part between brackets so it parses it as a sum. The first parameter of parseInt is the string containing the number (1.htm). We select this again by using substr. Now the starting location is the underscore + 1. The last argument is omitted since we can go till the end of the string. parseInt will parse 1.htm to 1. The second argument is used to force the function to use the decimal system. (radix 10). The last part of the sum adds one to the number. The result of this piece of code will be 2.
Appending it all together will give us:
http://stacksnippets.net/arr_2.htm
function urlGen(f) {
var i1 = "http://stacksnippets.net/arr_1.htm"; //cannot grab the url because of same origin policy
//var i1 = document.getElementById("iframe_id").contentWindow.location.href; //
var newURL = i1.substr(0,i1.lastIndexOf("_")+1) + (parseInt(i1.substr(i1.lastIndexOf("_")+1), 10)+1) + ".htm";
f.action = newURL;
return newURL;
}
//NOT PART OF THE SOLUTION:
document.body.onload = function() {
document.body.innerHTML += "Document initial url: http://stacksnippets.net/arr_1.htm";
var url = urlGen(new Object); //dummy object
document.body.innerHTML += "<br />Changed url: " + url;
}
Related
using jQuery; to add something to a url after the last /
for example add sale to:
/gender/category/brand/
so it becomes:
/gender/category/brand/sale
However due to the way the URL's are generated and built I can't just always say 'add it to the end of a URL' as there are sometimes ?query strings on the end for example:
/gender/category/brand/?collection=short&colour=red
I just can't figure out how I can add sale after the final / and always before a ?query string if one exists.
Searching through stackoverflow I've seen some bits about extracting content after the last / but not this, is this possible? I really would appreciate help getting this sorted.
EDIT - The solution
Thanks too all for your help but I was able to adapt Shree's answer the easiest to get this which did what I needed:
if(window.location.href.indexOf("sale") > -1) {
} else {
var raw = window.location.href;
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
window.location.href = newUrl;
}
Use substring with lastIndexOf.
var raw = '/gender/category/brand/?collection=short&colour=red';
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In vanilla javascript
var a = "/gender/category/brand/?collection=short&colour=red";
var lastIndexPosition = a.lastIndexOf('/');
a = a.substring(0,lastIndexPosition+1)
+"sale"
+a.substring(lastIndexPosition+1 , a.length);
console.log(a);
By using a reusable function in Javascript:
You can use lastIndexOf and get the last '/' index position and append your new data there.
The lastIndexOf() method returns the position of the last occurrence
of a specified value in a string.
Using this you can send any parameter into function there by it is reusable.
function insert(main_string, ins_string, pos) {
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var url = "/gender/category/brand/?collection=short&colour=red"
url = insert(url, 'sale', url.lastIndexOf("/") + 1)
console.log(url)
Here is a working DEMO
An alternative, use .split("?") to separate at the ? then combine them back, eg:
// Example with querystring
var url = '/gender/category/brand/?collection=short&colour=red'
var parts = url.split("?");
var newurl = parts[0] + "sale" + "?" + (parts[1]||"")
console.log(newurl)
// Test without querystring
var url = '/gender/category/brand/'
var parts = url.split("?");
var newurl = parts[0] + "sale" + (parts[1]||"")
console.log(newurl)
The (parts[1]||"") handles the case where there isn't a querystring.
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.).
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/
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());
}
});
});
hoping someone who knows a bit about javascript maybe able to help me. I need to extract part of the url of my pagepage to use in a javascript function and append to a url. ( it's for a power reviews setup.) the portion i need to extract is the number of the example below ie. www.mydomain.com/my-product-could-be-i950.html -- so would just need the 950 part.. the number part could be 2,3,4 characters. I then need to append this to the url www.mydomain.com/write-a-review.html?pr_page_id=950
could anyone help, it's a bit beyond me this one to be honest..
Many thanks.. Nathan
var num = location.pathname.match(/(\d+)\.html$/);
if( num ) {
var url = 'www.mydomain.com/write-a-review.html?pr_page_id=' + num[1];
}
Try this:
<script type="text/javascript">
function changeURL()
{
var szURL = location.pathname;
szURL = "www.mydomain.com/my-product-could-be-i950.html";
var num = szURL.replace(/\D/gi, "");
szURL = "www.mydomain.com/write-a-review.html?pr_page_id=" + num;
//Set URL
}
</script>
you could use regex:
var re = /i([0-9]{2,4})\.html$/;
var m = document.location.match(re);
if (m){
document.location.href = 'http://www.mydomain.com/write-a-review.html?pr_page_id='+m[1];
}
//current page URL
cur = window.location
//regex to match your number
regex = /i[0-9]{2,4}\.html/;
//your number
num = cur.match(regex);
alert(num);
Not tested, Note that the variable num could be an array.