I get users redirected to my site with GET parameters like this:
www.example.com/?email=mail#mail.com&vorname=name1+name2
I use javascript to populate my texfields (newsletter subscription) like this:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if(window.location.href.indexOf(parameter) > -1){
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
var vornametxt = getUrlParam('vorname','');
var emailtxt = getUrlParam('email','');
document.querySelector("input[name=nn]").value = vornametxt;
document.querySelector("input[name=ne]").value = emailtxt;
Like this it works properly but the parameter "vornametxt" contains plus signs if the GET parameter contains them. I want to replace the plus signs in the names with spaces which should work like this:
vornametxt = vornametxt.replace(/\+/g, " ");
That's what I found in older questions on stack overflow but it doesn't work.
What am I doing wrong? Is it possible that my wordpress site doesn't allow certain code?
I am using Wordpress and a plugin which allows me to add this javascript code to my sites footer.
Those values are URI-encoded with + meaning "space". To decode them, replace + with space and then use decodeURIComponent (to handle any other chars that have been encoded). I think it would go in your getUrlParam function, right at the end:
return decodeURIComponent(urlparameter.replace(/\+/g, " "));
Live Example:
(function() {
var window = {
location: {
href: "http://www.example.com/&email=mail#mail.com&vorname=name1+name2"
}
};
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
function getUrlParam(parameter, defaultvalue){
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return decodeURIComponent(urlparameter.replace(/\+/g, " "));
}
var vornametxt = getUrlParam('vorname','');
var emailtxt = getUrlParam('email','');
document.querySelector("input[name=nn]").value = vornametxt;
document.querySelector("input[name=ne]").value = emailtxt;
})();
<input type="text" name="nn">
<br><input type="text" name="ne">
Related
I have an AngularJs filter returning the domain name of a given URL string.
app.filter('domain', function() {
return function(input) {
if (input) {
// remove www., add http:// in not existed
input = input.replace(/(www\.)/i, "");
if (!input.match(/(http\:)|(https\:)/i)) {
input = 'http://' + input;
})
var url = new URL(input);
return url.hostname;
}
return '';
};
});
the problem is that because I doesn't support URL() method, it doesn't work in IE.
Yes, according to this document IE doesn't support URL() interface. but let's get out of box! your filter could be written in more short and fast way:
app.filter('domain', function() {
return function(input) {
if (input) {
input = input.replace(/(www\.)/i, "");
if( !input.replace(/(www\.)/i, "") ) {
input = 'http://' + input;
}
var reg = /:\/\/(.[^/]+)/;
return input.match(reg)[1];
}
return '';
};
});
Hi i am new in javascript before i read the case split using the function. I just followed but not understand it. Can you guys give me a link or guide to explain how it work? tks a ton
var first = getUrlVars()["id"];
var second = getUrlVars()["page"];
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
This function return the value of each varrian from url.
In your code, you want to get id, page from url. I guest you have a url like : your-page?id=value&page=value, and you want to get them, don't you?
You need to read the replace function at http://www.w3schools.com/jsref/jsref_replace.asp
There is a kind of function you would like. Hope you will understand this :
var getUrlVars = function( url ){
if( !url.match( /\?/ ) ) return {};
var paramsfull = url.replace( /^.*\?/, "" ).split( /\&/g );
var params = {};
var _temp;
for( var p in paramsfull ){
_temp = paramsfull[ p ].split( /\=/ );
params[ _temp[ 0 ] ] = _temp[ 1 ];
}
return params;
}
var first = getUrlVars( window.location.href )[ "id" ];
var second = getUrlVars( window.location.href )[ "page" ];
Is there any javascript function, to parse the first line of the http header?
GET /page/?id=173&sessid=mk9sa774 HTTP/1.1
The url is encoded.
I would like to get an object, like this:
{
"method" : "GET",
"url" : "/page/",
"parameters": {
"id" : 173,
"sessid" : "mk9sa774"
}
}
I searched a lot, but I haven't found anything useful.
thanks in advance,
First you can split on spaces:
var lineParts = line.split(' ');
Now you can get the method, unparsed path, and version:
var method = lineParts[0];
var path = lineParts[1];
var version = lineParts[2];
Then you can split up the path into the query string and non-query string parts:
var queryStringIndex = path.indexOf('?');
var url, queryString;
if(queryStringIndex == -1) {
url = path, queryString = '';
}else{
url = path.substring(0, queryStringIndex);
// I believe that technically the query string includes the '?',
// but that's not important for us.
queryString = path.substring(queryStringIndex + 1);
}
If there is a query string, we can then split it up into key=value strings:
var queryStringParts = [];
if(queryStringIndex != -1) {
queryStringParts = queryString.split('&');
}
Then we can unescape them and stuff them into an object:
var parameters = {};
queryStringParts.forEach(function(part) {
var equalsIndex = part.indexOf('=');
var key, value;
if(equalsIndex == -1) {
key = part, value = "";
}else{
key = part.substring(0, equalsIndex);
value = part.substring(equalsIndex + 1);
}
key = decodeURIComponent(key);
value = decodeURIComponent(value);
parameters[key] = value;
});
If you really wanted to, you could then put all that data into an object:
return {
method: method,
url: url,
version: version,
parameters: parameters
};
If you're in a browser environment, that's the only way to do it. If you're using Node.JS, it can deal with the URL parsing for you.
I would like to redirect a user to a target URL on a button click. The target URL is variable and has to be read from the current page URL parameter 'source':
For instance, I have a url http://w/_l/R/C.aspx?source=http://www.google.com
When the user clicks on a button he's being redirect to http://www.google.com
How would I do that with jQuery?
first of all you need to get the url param : source
this can be done with a function like :
function GetParam(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
// you can use it like
var source = GetParam('source');
//then
window.location.href = source
On button click handler, just write window.location.href = http://www.google.com
You will need to parse the query string to get the value of the variable source.
You don't need jQuery for it.
A simple function like this will suffice:
function getFromQueryString(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
location.href = getFromQueryString("source");
Using the url parsing code from here use this to parse your url (this should be included once in your document):
var urlParams = {};
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
Then do this to redirect to the source parameter:
window.location.href = urlParams["source"];
Since you are using the jQuery framework, I'd make use of the jQuery URL Parser plugin, which safely parses and decodes URL parameters, fragment...
You can use it like this:
var source = $.url().param('source');
window.location.href = source;
get url params : (copied from another stackoverflow question) :
var params= {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
window.location = params['source'];
You can do like this,
<a id="linkId" href=" http://w/_l/R/C.aspx?source=http://www.google.com">Click me</a>
$('#linkId').click(function(e){
var href=$(this).attr('href');
var url=href.substr(href.indexof('?'))
window.location =url;
return false;
});
I am (slowly) writing an XML parser for some "site definition" files that will drive a website. Many of the elements will be parsed in the same manner and I won't necessarily need to keep the values for each.
The XML
The parser so far
My question is actually pretty simple: How can I use jquery manipulators in an class function? How can I pass $(this)? I know that it sometimes refers to a DOM object and sometimes the jQuery object, but am a bit hazy.
For my function:
function parseXML(xml) {
$("book, site", xml).children().each(function() {
var label = $(this).get(0).tagName;
var text = $(this).text();
var key = toCamelCase(label);
if ((key in siteData) && (text != -1)){
if (isArray(siteData[key]))
{
$(this).children().each(function (){
var childLabel = $(this).get(0).tagName;
var childText = $(this).text();
var childKey = toCamelCase(childLabel);
if(isArray(siteData[key][childKey]))
{
siteData[key][childKey].push(childText);
}
else {
siteData[key].push(childText);
}
});
}
else
{
siteData[key] = text;
}
};
});
}
});
I want to place
var label = $(this).get(0).tagName; var text = $(this).text(); var key = toCamelCase(label);
in a class, so I can do something like
var child = new Element(); and var subchild = new Element();
and then use child.label , child.text and child.key...
But again, not sure how to use the jquery methods with these... I have more nodes to process and I don't want to keep doing stuff like var label = $(this).get(0).tagName; and then var childLabel = $(this).get(0).tagName;
Thanks.
var app = {};
app.element = function(data) {
return function() {
var _text = data.get(0).tagName, _label= data.text(), _key = toCamelCase(_label);
var that = {};
that.label = function() {
return _label;
}
that.text = function() {
return _text;
}
that.key = function() {
return _key;
}
return that;
}();
};
app.instanceA = app.element($(this));
document.writeln(app.instanceA.label());
Ok so this works but, I'm not sure if it's the best way.