I have this function from a previous problem, and it works great however I just realized my collection of links need to have the base URL stripped out.
These are the parts which I thought would strip out the baseURL:
baseUrlPattern = /^https?:\/\/[a-z\:0-9.]+/; // create the regexp
link.href.replace(baseUrlPattern ,""); // then use replace to strip it out of the URL
UPDATE
I should have mentioned:
The function already can discover the link and apply the attribute, but doesn't strip out the base URL.
This:
link1
Should look like this in the DOM afterwards:
link1
JS:
var URLChecker = (function iffe() {
var publicAPI = {
getURL: function() {
for (var i = 0; i < arguments.length; i++) {
return {
'smo': 'http://url.nyc.com',
'smodev': 'http://smodev.rye.foo.com',
'url1_sans_3w': 'http://url1.com',
'url2': 'http://www.url2.com',
'url3': 'http://www2.url3.com'
}[arguments[i]];
}
},
searchURL: function() {
var link, url, baseUrlPattern = /^https?:\/\/[a-z\:0-9.]+/;
for (var i = 0, len = arguments.length; i < len; i++) {
url = this.getURL(arguments[i]);
for (var j = 0, jlen = document.links.length; j < jlen; j++) {
link = document.links[j];
if (link.href.indexOf(url) !== -1) {
link.setAttribute("target", "_blank");
link.href.replace(baseUrlPattern ,"");
}
}
}
}
};
return publicAPI;
})();
HTML:
link1
<br>
link2
<br>
link3
<br>
link4
<br>
link5
Using native methods:
var url = 'http://url.nyc.com/x/xx/xxx';
var strippedUrl = new URL(url); // url.pathname == '/x/xx/xxx/'
Note: this may not work in Chrome; but browser wasn't specified
There's different ways you can go about this, here's one of them:
See comments below
searchURL: function() {
var link, url, parser; //added parser
for (var i = 0, len = arguments.length; i < len; i++) {
url = this.getURL(arguments[i]);
for (var j = 0, jlen = document.links.length; j < jlen; j++) {
link = document.links[j];
if (link.href.indexOf(url) !== -1) {
// create a dummy link just to get the pathname of the actual link
parser = document.createElement('a');
parser.href = link.href;
link.setAttribute("target", "_blank");
link.href = parser.pathname;
}
}
}
}
Should you need anything else, remember the parser just an anchor so you have the following
var href = "http://url.nyc.com/xxx/xxx/xxx";
parser = document.createElement('a');
parser.href = href;
console.dir(parser);
parser.protocol; // => "http:"
parser.hostname; // => "url.nyc.com"
parser.port; // => ""
parser.pathname; // => "/xxx/xxx/xxx"
parser.search; // => ""
parser.hash; // => ""
parser.host; // => "url.nyc.com"
Maybe it's late but if you want
This:
link1
Should look like this in the DOM afterwards:
link1
you can do this way
var x = 'http://url.nyc.com/xxx/xxx/xxx';
var y = x.split('/').slice(3).join('/');
console.log(y);
Related
I have a onload function to split a data from the current URL.
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
I need to use the split value from windows.onload event to a function
var te='https://myurl.html?AID=' + data; //need to use the split value here
Something like this?
const url = new URL(document.location.href);
window.addEventListener('DOMContentLoaded', () => { // page load
document.getElementById('here').innerHTML = url.searchParams.get('name'); // gets the &name=whatever
const te = `https://myurl.html?AID=${url.searchParams.get('AID')}`; // gets the AID=whatever
})
I see in MathJax they include the script like this.
<script type="text/javascript" src="path-to-MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
Is there a way to get the config parameter in javascript?
The only way to get that URL is to search the current document and find that particular <script> tag and then get the .src property from the script tag and then parse it to get the config parameters.
Scripts are loaded into the global browser namespace and don't have any properties or variables that are unique to a particular script. You could use something like this:
function findScript(tagToMatch) {
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src.indexOf(tagToMatch) !== -1) {
// scripts[i].src is the full URL
return scripts[i].src;
}
}
}
And, then you could use that generic function to find your particular tag and parse out the config value like this:
function findConfig() {
var url = findScript("/MathJax.js?"), matches;
if (url) {
matches = url.match(/[&?]config=([^&$]+)/);
if (matches) {
return matches[1];
}
}
return null;
}
var cfg = findConfig();
And, here's a working snippet:
function findScript(tagToMatch) {
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src.indexOf(tagToMatch) !== -1) {
// scripts[i].src is the full URL
return scripts[i].src;
}
}
}
function findConfig() {
var url = findScript("/MathJax.js?"), matches;
if (url) {
matches = url.match(/[&?]config=([^&$]+)/);
if (matches) {
return matches[1];
}
}
return null;
}
document.write(findConfig());
<script type="text/javascript" src="path-to-MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
You can use regular expressions and plain-old-javascript to extract the config parameter, but if you're using jQuery there are more elegant ways of isolating the element you need.
function extractMathJaxConfig() {
var scripts = document.getElementsByTagName("script")
var regex = /config=([^&]+)/
for (var i = 0; i < scripts.length; ++i) {
var src = scripts[i].src;
if (src.indexOf("MathJax.js") != -1) {
var results = regex.exec(src);
if (results) return results[1];
}
}
}
console.log(extractMathJaxConfig());
JSFiddle: https://jsfiddle.net/vdqvjnbw/
You won't get that parameter via your script that you're requesting in that script tag, here's why:
The binary representation of the JS code will not be loaded into memory until the browser has pulled those bytes into the page. Meaning, that JS is basically just a text file out on the server until its downloaded by the browser and interpreted; the JavaScript has no behavior until then.
However, inside of your page -- if you'd like to strip that query param from the src attribute of your script tag -- you can do something like this:
function getURIComponents(uri) {
var a = document.createElement('a');
a.href = uri;
return {
origin: a.origin,
search: a.search
};
}
function getParams(uri) {
var c = getURIComponents(uri);
var pairs = c.search.split('?')[1].split('&');
var params = {};
for (var i = 0, len = pairs.length; i < len; i++) {
var pair = pairs[i].split('=');
var name = pair[0];
var value = pair[1];
params[name] = value;
}
return params;
}
getParams(document.getElementByTagName('script').src);
This [untested] code should give you an object containing a key config with what value has been set for it.
Hope this helps.
I'd like to preface I'm a total beginner with JS, only been working with it for a few days now.
Here's what I'm working with http://jsfiddle.net/joyroyxw/
What I want to do is get a person's name and display images of each letter in their name.
So far I'm able to split the name into the individual letters, and concatenate "letter," as search tags, so that flickr returns images of each letter.
My problem is these images are not being added in order, could this be because one query loads faster than another? How could I add a buffer or delay so that each letter is displayed in order? Why would it do that if my for loop is sending the tags to the function in order?
Javascript from jsfiddle:
function getQueryStringVar(name){
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i=0 ; i < props.length;i++){
var pair = props[i].split("=");
if(pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag){
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: tag,
tagmode: "all",
format: "json"
})
.done(function (flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
console.log(url);
$("body").append("<img src="+ url + "></img>");
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek";
var str = "letter,";
var searchtags = new Array()
for (var i = 0; i < name.length; i++) {
//console.log(str.concat(searchtags.charAt(i)));
searchtags[i] = str.concat(name.charAt(i));
}
for (var j = 0; j < name.length; j++){
//getLetterImage(searchtags[j]);
getLetterImage(searchtags[j]);
}
});
Instead of using append, try having a place holder element already build to receive the data.
<div id="img1">Loading</div>
<div id="img2">Loading</div>
<div id="img3">Loading</div>
You can dynamically create the elements as needed with javascript. Then you populate them in the order. Simply increment i as you go.
$("#img"+i).html("<img src="+ url + "></img>");
UPDATE
Your jsfiddle was very close, but you have to remember that ajax is asynchronous.
html
<body>
<h1>Hi! What's your name?</h1>
<form action="trending.html">
<input class="textbox" type="text" name="name">
</form>
<div id="img0">Loading</div>
<div id="img1">Loading</div>
<div id="img2">Loading</div>
<div id="img3">Loading</div>
<div id="img4">Loading</div>
</body>
javascript
function getQueryStringVar(name){
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i=0 ; i < props.length;i++){
var pair = props[i].split("=");
if(pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag, theNumber){
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
return $.getJSON( flickerAPI, {
tags: tag,
tagmode: "all",
format: "json"
})
.then(function (flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
$("#img"+theNumber).html("<img src="+ url + "></img>");
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek Martin";
var str = "letter,";
var searchtags = new Array()
for (var i = 0; i < name.length; i++) {
searchtags[i] = str.concat(name.charAt(i));
}
for (var j = 0; j < name.length; j++){
getLetterImage(searchtags[j], j);
}
});
I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(url) {
var vars = [],hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});
What's the best way to open all external links (URLs that don't match the current domain) in a new tab using JavaScript, without using jQuery?
Here's the jQuery I'm current using:
// Open external links in new tab
$('a[href^=http]').click(function () {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
window.open(this.href);
return false;
}
});
Pure JS:
function externalLinks() {
for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
var b = c[a];
b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
}
}
;
externalLinks();
The links property returns a collection of all <area> and <a> elements in a document with a value for the href attribute.
var links = document.links;
for(var i = 0; i < links.length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Document/links
Add a target="_blank" to the tag. You could do that in the pre-processor (e.g. PHP) or in a JS during the onload event.
$("a[href^=http]").each(function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr({
target: "_blank",
title: "Opens in a new window"
});
}
})
This script should work for you.
UPDATE : try this fiddle http://jsfiddle.net/sameerast/GuT2y/
JS version
var externalLinks = function(){
var anchors = document.getElementsByTagName('a');
var length = anchors.length;
for(var i=0; i<length;i++){
var href = anchor[i].href;
if(href.indexOf('http://sample.com/') || href.indexOf('http://www.sample.com/')){
return;
}
else{
anchor[i].target='_blank';
}
}
};