i have for example this URL
www.mypage/SessionPage.aspx?session=session%202#b
using this code i can track the complet URL
_gaq.push(['pageTrackerTime._trackEvent', 'category', 'action', document.location.href, roundleaveSiteEnd]);
BUt i would like only to take part of it like session%202
is there a way to do this in JavaScript
Use regular expression
function getSessionId() {
var re = /session=([^&=]+)/g;
var match = re.exec(document.location.href);
if (match) {
var sessionId = match[1];
return sessionId;
}
return null;
}
Related
I have a DataTable and I want to change language of the datatable if the user selects an English version of the site I want to translate datatable to English, or Spanish.
So far my code looks like this:
var langMap = {
en: {
path: 'English',
mods: {
sLengthMenu: "Display _MENU_ records per page - custom test"
}
},
es: {
path: 'Spanish',
mods: {
sLengthMenu: "Mostrar _MENU_ registros - algo muy especial..."
}
}
};
function getLanguage() {
var lang = 'es' //$('html').attr('lang');
var result = null;
var path = '//cdn.datatables.net/plug-ins/1.10.13/i18n/';
$.ajax({
async: false,
url: path + langMap[lang].path + '.json',
success: function(obj) {
result = $.extend({}, obj, langMap[lang].mods)
}
})
return result
}
What I am trying to achieve is this value var lang = 'es' not be hardcoded so, I want to check if the URL contains /es or /en and update that value.
Something like this:
function getLanguage() {
if ( document.location.href.indexOf('/en') > -1 ) {
var lang = 'es';
}
var result = null;
var path = '//cdn.datatables.net/plug-ins/1.10.13/i18n/';
$.ajax({
async: false,
url: path + langMap[lang].path + '.json',
success: function(obj) {
result = $.extend({}, obj, langMap[lang].mods)
}
})
return result
}
Can somebody try to help me with this?
As long as you aren't supporting should-be-dead browsers (i.e. IE), and if it is part of the query string, you can use URLSearchParams for this.
const qs = window.location.search;
const params = new URLSearchParams(qs);
const lang = params.get('lang');
If it's part of the url itself, then you'll have to parse your url. You can use the window.location.pathname to get your url path without the domain. Say it looks like this: https://my.domain.com/some/path/en
// remove prepended '/', then break it up
const pathbits = window.location.pathname.slice(1).split('/');
const lang = pathbits[2];
You can use this function parse_query_string() from this answer https://stackoverflow.com/a/979995/6426512 to get your parameters
then do some simple logic like this
var query_string = window.location.search.substring(1);
var lang = parse_query_string(query_string);
if ( lang==='es') {
//do something;
}
else{
//do something
}
But note this is for newer browsers like the referenced answer says. For older browsers (including Internet Explorer), you can use https://github.com/ungap/url-search-params or the code from the original version of this answer that predates URL:
I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
i have a code like this and i get "Uncaught TypeError: Cannot call method 'replace' of undefined" in console, im not so good at javascript
<script>
parse_tag = function (str) {
var create_link = function (url, text) {
var link = $("<a>", {
text: text,
href: url,
target: "_blank"
});
return link.prop('outerHTML');
};
// parse username
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://twitter.com/" + s.replace('#', ''), s);
});
// parse hashtags
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://search.twitter.com/search?q=" + s.replace('#', ''), s);
});
return str;
};
$(document).ready(function() {
var text = $('.desc');
parse_tag(text);
});
</script>
You are calling the function like
var text = $('.desc');
parse_tag(text);
And the function is
parse_tag = function (str) { // <-- str suppose to be a string
var create_link = function(url, text){
// ...
return link.prop('outerHTML');
}
//...
str = str.replace(/[#]+[A-Za-z0-9_]+/g, function (s) {
return create_link("http://twitter.com/" + s.replace('#', ''), s);
});
}
In this case, str should be string but according to var text = $('.desc'); it's a jQuery object so you can change either var text = $('.desc'); to var text = $('.desc').text(); or make changes in your parse_tag function, otherwise, you'll get error something like object doesn't support this property or method.
Also, you are using two regex as /[#]+[A-Za-z0-9_]+/g, and /[#]+[A-Za-z0-9_]+/g but both are being used on a link, something like
#me`
Because you are returning an a tag using
return link.prop('outerHTML');
So, make changes in your regex too or maybe it's better to use the replace on link's text/href, so make sure you make the changes.
I am using following function to parse YouTube URL to retrieve a YouTube ID from a YouTube URL:
function yt_parser()
{
var yt_url_sub = http://www.youtube.com/watch?v=6nZlXB5okeo;
var youtube_id = yt_url_sub.replace(/^[^v]+v.(.{11}).*/,"$1");
alert(youtube_id);
}
output : 6nZlXB5okeo
but how should I validate whether this URL is from YouTube or not?
You can change your regex for this
var url = 'http://www.youtube.com/watch?v=wBnCURIfbPg'
var m = url.match(/:\/\/www.youtube.com\/.*?\bv=([^&]+)/);
if (m) {
alert(m[1]);
}
http://jsfiddle.net/zmDZp/
Inside a web worker, I have an html string like:
"<div id='foo'> <img src='bar'></img> <ul id='baz'></ul> </div>"
Is there any library I can import to easily access id and src attributes of the different tags ? Is regex the only way inside a worker ?
There are two ways to solve this problem efficiently:
Regex
With the risk of getting false positives, you can use something like:
var pattern = /<img [^>]*?src=(["'])((?:[^"']+|(?!\1)["'])*)(\1)/i;
var match = string.match(pattern);
var src = match ? match[2] : '';
Built-in parser & messaging
If getting the HTML right is a critical requirement, just let the browser parse the HTML, by passing the string to the caller. Here's a full example:
Caller:
var worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {
if (!e.data) return;
if (e.data.method === 'getsrc') {
// Unlike document.createElement, etc, the following method does not
// load the image when the HTML is parsed
var doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = e.data.data;
var images = doc.getElementsByTagName('img');
var result = [];
for (var i=0; i<images.length; i++) {
result.push(images[i].getAttribute('src'));
}
worker.postMessage({
messageID: e.data.messageID,
result: result
});
} else if (e.data.method === 'debug') {
console.log(e.data.data);
}
});
worker.js
// A simple generic messaging API
var callbacks = {};
var lastMessageID = 0;
addEventListener('message', function(e) {
if (callbacks[e.data.messageID]) {
callbacks[e.data.messageID](e.data.result);
}
});
function sendRequest(method, data, callback) {
var messageID = ++lastMessageID;
if (callback) callbacks[messageID] = callback;
postMessage({
method: method,
data: data,
messageID: messageID
});
}
// Example:
sendRequest('getsrc',
'<img src="foo.png">' +
"<img src='bar.png'>" +
'<textarea><img src="should.not.be.visible"></textarea>',
function(result) {
sendRequest('debug', 'Received: ' + result.join(', '));
}
);