I'm trying to get the page name of the iframe page (that is on the same server) and if it's not the following name(s): 'index1.php' or 'indexTOM.php' then don't do anything if it is that page name then reload the iframe. Here is now I have it set but it doesn't work for some reason the resultNfo is always true and the iframe never reloads?
//Check URL of IFRAME
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var word = 'index1.php';
var regex = new RegExp( '\\b' + word + '\\b' );
var resultNfo = regex.test( currentUrl );
if (resultNfo = true){ document.getElementById("frmcontent").contentDocument.location.reload(true); }
var word = 'indexTOM.php';
var regex = new RegExp( '\\b' + word + '\\b' );
var resultNfo = regex.test( currentUrl );
if (resultNfo = true){ document.getElementById("frmcontent").contentDocument.location.reload(true); }
alert('URL is: '+currentUrl+'\n'+resultNfo);
Why don't you just do resultNfo = currentUrl.indexOf('indexTOM.php') !== -1 ?
You also have a lot of problems here, you should use a for loop really
Not tested demo
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for( var i = 0; i < urls.length; i++ ) {
var url = urls[i];
if( frame.location.href.indexOf(url) !== -1 ) {
frame.location.reload()
}
}
Try something along the lines of the above code, it's a lot cleaner.
Related
I want to fetch all urls available in paragraph or sentence in javascript in array. For example check paragraph below:
Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.
From above string, We have to get array of these two url.Solution 1: Solution 1, I know is to split paragraph with space, iterate over array and check for url one by one and push into url's array. But, It's a time taking solution.Are there better solution for finding it or above solution is fastest and good to go?Thank you.
Is this what you are looking for?
var list = [];
var sentence = "Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.";
var result = checkForURL(sentence);
function checkForURL(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function (url) {
return '<a>' + url + '</a>';
})
}
var number = result.split('<a>');
for (var i = 1; i < number.length; i++) {
list.push(number[i].split(".</a>")[0]);
}
alert(list);
You might want to split on :// to get a smaller array to iterate over.
Example:
Demo
JSFiddle
HTML
<p id='p'>
Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.
</p>
<h4>
URLs
</h4>
<ol id='results'>
</ol>
Javascript
findUrls();
function findUrls(){
var p = document.getElementById('p');
var res = document.getElementById('results');
var pStr = p.innerText;
var parts = pStr.split(/:\/\//);
if (parts.length < 2)
return;
for (var i = 1 ; i < parts.length ; i++){
var part = parts[i];
var lastPart = parts[i-1];
if (lastPart.length < 4 )
continue;
if (lastPart.length >= 4 && lastPart.substr(-4) == 'http')
part = 'http://' + part;
else if (lastPart.length >= 5 && lastPart.substr(-5) == 'https')
part = 'https://' + part;
var firstSpace = part.indexOf(' ');
if (firstSpace > -1)
part = part.substring(0, firstSpace);
var lastChar = part.charAt(part.length - 1);
if (lastChar == ',' || lastChar == '.' /* || ... */)
part = part.substring(0,part.length - 1);
res.innerHTML += '<li>' + part + '</li>'; // or push part to some result array
}
}
Try this approach. It might need some fine tuning..
var paragraphs = document.getElementsByTagName('p')
var regex = /(https?:\/\/.*?)(\s|$)/g;
var urls = [];
var badLastChars = [".", ","];
for (var i = 0; i < paragraphs.length; i++) {
var p = paragraphs[i].innerText;
var match;
while (match = regex.exec(p)) {
var url = match[1];
var lastChar = url[url.length-1];
if (badLastChars.indexOf(lastChar) > -1 ) {
url = url.slice(0,url.length-1);
}
console.log(url);
urls.push(url);
}
}
<p> Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.</p>
<p> Another paragraph https://stackexchange.com. and here is another url I am making up: https://mycoolurlexample.com/this/is/an/example</p>
For an affiliate with affiliate ID ‘xxxx’, the tracking parameters are:
?utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=xxxx
If the URL already contains a ‘?’ (Example: www[dot]companyname[dot]com/products/mobiles-mobile-phones?sort=date), the tracking parameter to be appended should be:
&utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=xxxx
what I am using is this script to append my affiliate tag to the URL
var links = document.getElementsByTagName('a');
for (var i = 0, max = links.length; i < max; i++) {
var _href = links[i].href;
if (_href.indexOf('amazon.in') !== -1) {
links[i].href = _href + '?&tag=geek-21';
}
else if (_href.indexOf('snapdeal.com') !== -1) {
links[i].href = _href + '?utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=10001';
}
}
if the URL already contains '?' how can I use my above script to tag the '&' as a starting of affiliate tag? like this
&utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=10001
see this image for better understanding
Well, just like you said. Check if the href contains ? and set the appropriate charcter in front of you parameter list:
for (var i = 0, max = links.length; i < max; i++) {
var _href = links[i].href;
// this is how to check and set for the appropriate starting character of your parameter list
var startChar = _href.indexOf("?") === -1 ? "?" : "&";
if (_href.indexOf('amazon.in') !== -1) {
links[i].href = _href + startChar +'tag=geek-21';
}
else if (_href.indexOf('snapdeal.com') !== -1) {
links[i].href = _href + startChar + 'utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=10001';
}
}
To replace ? with & for urls with affiliate tag (as a preceding character for utm_source parameter) if a question mark ? already occurs within a url - use the following approach with String.prototype.replace() function and specific regex pattern:
var _href = 'www[dot]companyname[dot]com/products/mobiles-mobile-phones?sort=date?utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=xxxx',
_href = _href.replace(/(?=.*?\?.*?)\?(utm_source=)/, '&$1');
console.log(_href);
Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});
jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];
This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}
I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199
I have a:
var pageURL = location.href; // stores the URL of the current page in the var pageURL
And I have :
var Page = Array ();
page [0] = "http://web1.com"
page [1] = "http://web2.com"
page [2] = "http://web3.com"
Now I want to make a function (called nextPage) to check which one of these pages in the array equals the PageURL. Also I need to have a button, so when I click it it will take me to the next page. What that mean I want to increment the page by 1.
You can use very simply
var current = page.indexOf(location.href);
Then to go to the next page
location.href = page[current + 1];
var form = document.createElement('form');
form.id = "nextForm";
document.body.appendChild(form);
var nextButton = document.createElement('input');
nextButton.type = 'button';
nextButton.id = 'nextButton';
nextButton.value = 'Next Button';
nextButton.onclick = nextPage;
form.appendChild(nextButton);
function nextPage() {
var page = Array ();
page[0] = "http://web1.com" // insert your urls here
page[1] = "http://web2.com"
page[2] = "http://web3.com"
var matchIndex = page.indexOf(location.href);
var nextIndex;
if (matchIndex !== -1 && page[matchIndex + 1]) {
nextIndex = matchIndex + 1;
} else {
alert("You're at the last page"); // next page in the array does not exist, you can handle the error however you want
return;
}
goToNextPage(page[nextIndex]);
}
function goToNextPage(url) {
document.location.href=url;
}
Based on Joseph's answer the full code would look something like this:
function goToNextPage() {
var currentPageUrl = location.href;
var pageUrls = [
"http://web1.com",
"http://web2.com",
"http://web3.com"
];
var currentIndex = pageUrls.indexOf(location.href);
var nextIndex = currentIndex + 1;
var nextPageUrl = pageUrls[nextIndex];
location.href = nextPageUrl;
}
Also if support for indexOf is an issue for you in IE check out the answer to that from another StackOverflow question: How to fix Array indexOf() in JavaScript for Internet Explorer browsers
So, I was messing around with this Dynamic Breadcrumbs write-up, and came across an issue where if the directory name has a space in it, then %20 gets added to the actual visible breadcrumb. Would this be removed using the decodeURI() function or is there a better way?
Here's the js:
var crumbsep = " • ";
var precrumb = "<span class=\"crumb\">";
var postcrumb = "</span>";
var sectionsep = "/";
var rootpath = "/"; // Use "/" for root of domain.
var rootname = "Home";
var ucfirst = 1; // if set to 1, makes "directory" default to "Directory"
var objurl = new Object;
// Grab the page's url and break it up into directory pieces
var pageurl = (new String(document.location));
var protocol = pageurl.substring(0, pageurl.indexOf("//") + 2);
pageurl = pageurl.replace(protocol, ""); // remove protocol from pageurl
var rooturl = pageurl.substring(0, pageurl.indexOf(rootpath) + rootpath.length); // find rooturl
if (rooturl.charAt(rooturl.length - 1) == "/") //remove trailing slash
{
rooturl = rooturl.substring(0, rooturl.length - 1);
}
pageurl = pageurl.replace(rooturl, ""); // remove rooturl from pageurl
if (pageurl.charAt(0) == '/') // remove beginning slash
{
pageurl = pageurl.substring(1, pageurl.length);
}
var page_ar = pageurl.split(sectionsep);
var currenturl = protocol + rooturl;
var allbread = precrumb + "" + rootname + "" + postcrumb; // start with root
for (i=0; i < page_ar.length-1; i++)
{
var displayname = "";
currenturl += "/" + page_ar[i];
if (objurl[page_ar[i]])
{
displayname = objurl[page_ar[i]];
}
else
{
if (ucfirst == 1)
{
displayname = page_ar[i].charAt(0).toUpperCase() + page_ar[i].substring(1);
}
else
{
displayname = page_ar[i];
}
}
if ( i < page_ar.length -2 )
{
allbread += precrumb + crumbsep + "" + displayname + "" + postcrumb;
}
else
{
allbread += crumbsep + displayname;
}
}
document.write(allbread);
If decodeURI() was to be used, where exactly would it go? Also, more unrelated, would there be an option you could add to the code above that would make the actual page inside of the directory be included in the breadcrumbs as the last item instead of the last directory? Not real important but thought I would ask as well. Thanks for any input!
Yes, decodeURI will do the trick. You can add the line displayname = decodeURI(displayname); right before the if that reads if ( i < page_ar.length -2 ):
...
displayname = decodeURI(displayname);
if ( i < page_ar.length -2 )
...
Note that since displayname and currenturl end up being directly embedded in a raw HTML string, any special HTML characters should be escaped first, otherwise you're open to some XSS attacks (imagine some malicious individual posting a link to your site like yoursite.com/valid/page/%3Cscript%3Ealert%28%22Oh%20no%2C%20not%20XSS%21%22%29%3C%2Fscript%3E). One of the simplest ways to do so is covered by this answer, though it requires jQuery.
If you want the current page included in the breadcrumbs, I believe it is sufficient to change the loop to go from 0 to page_ar.length instead of page_ar.length - 1:
...
for (i=0; i < page_ar.length; i++)
...
You should use decodeURIComponent(), not decodeURI() for this. It's a little hard to see what you're trying to do, but here's some simpler code that will give you an array of the 'directories' in the current URI, decoded:
var dirs = location.pathname.split('/');
for (var i=0,len=dirs.length;i<len;++i){
dirs[i] = decodeURIComponent(dirs[i]);
}