This is working fine if i am writing jpg|png|jpeg|gif here...
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
alert('Error: extension is not allowed!' + Extensions + ' file ext: ' + ext);
return false;
}
If i use variable instead of static then it is not working
var Extensions = "jpg|png|jpeg|gif";
if (!(ext && /^(Extensions)$/.test(ext))) {
alert('Error: extension is not allowed!' + Extensions + ' file ext: ' + ext);
return false;
}
Thanks in advance
Imdadhusen
You should do it like this:
(new RegExp("jpg|png|jpeg|gif")).test(ext)
You are using invalid syntax for the regular expression. If you are going to store it in a variable, you must still use your regular expression from your first example.
So:
var Extensions = /^(jpg|png|jpeg|gif)$/;
if (!(ext && Extensions.test(ext)))
will work. Your second example is trying to match the word 'Extensions'.
it wont get error
var Extensions = "/^(jpg|png|jpeg|gif)$/";
if (!(ext && Extensions.test(ext))) {
alert('Error: extension is not allowed!' + Extensions + ' file ext: ' + ext);
return false;
}
To use a variable, you need to use the RegExp object:
new RegExp('^(' + Extensions + ')$').test(ext)
Or assign the entire regex into your variable:
var Extensions = /^(jpg|png|jpeg|gif)$/;
Extensions.test(ext)
Perhaps call it allowedExtensions or something though.
Try this:
var Extensions = /^(jpg|png|jpeg|gif)$/;
if (!(ext && Extensions.test(ext))) {
alert('Error: extension is not allowed!' + Extensions + ' file ext: ' + ext);
return false;
}
Related
Cant send parameter containing "#" to dot net web service from ajax.
var s = encodeURI(
"http://subdomain.mydomain.domain.asmx/getData?OUserId=" + UserId +
"&Token=" + Token +
"&OrgId=" + OrgId +
'&Message=' + Message +
'&Schoolid=' + SchoolId +
'&SessionId=" ' + SessionId +
'&UnicodeValue=' + UnicodeValue +
'&ClassID=' + ClassIdCommaSeparated.toString()
);
$.ajax({
url: s,
error: function(err) {
alert(err);
},
success: function(data) {....
}
});
Here classIdCommaSeparated is 1#1#1#1#1,1#1#1#1#1,1#1#1#1#1.
Use encodeURIComponent on the individual parts, rather than encodeURI on the whole:
var s = "http://subdomain.mydomain.domain.asmx/getData?OUserId=" + encodeURIComponent(UserId) +
"&Token=" + encodeURIComponent(Token) +
"&OrgId=" + encodeURIComponent(OrgId) +
'&Message=' + encodeURIComponent(Message) +
'&Schoolid=' + encodeURIComponent(SchoolId) +
'&SessionId=" ' + encodeURIComponent(SessionId) +
'&UnicodeValue=' + encodeURIComponent(UnicodeValue) +
'&ClassID=' + encodeURIComponent(ClassIdCommaSeparated.toString());
$.ajax({
url: s,
error: function(err) {
alert(err);
},
success: function(data) {....
}
});
Technically, both the name (before the =) and the value (after the =) need to be encoded, but when your names consist just of the letters A-Z (in upper or lower case) or digits, like yours do, encoding them doesn't change them at all. (If you didn't know what those names were, you'd definitely want to pass them through encodeURIComponent.)
several hours after i am not able to understand what is arising this problem.but i have worked around to have a temporary solution to the problem.i have used underscore in place of # and i got it working.thanks #T.J. Crowder for having a look upon.
I am trying to analyze anchor links ( their text property ) in PhantomJS.
The retrieval happens here:
var list = page.evaluate(function() {
return document.getElementsByTagName('a');
});
this will return an object with a property length which is good (the same length I get when running document.getElementsByTagName('a'); in the console). But the vast majority of the elements in the object have the value of null which is not good.. I have no idea why this is happening.
I have been playing with converting to a real array thru slice which did no good. I have tried different sites, no difference. I have dumped the .png file to verify proper loading and the site is properly loaded.
This is obviously not the full script, but a minimal script that shows the problem on a well known public site ;)
How can I retrieve the full list of anchors from the loaded page ?
var page = require('webpage').create();
page.onError = function(msg, trace)
{ //Error handling mantra
var msgStack = ['PAGE ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
});
}
console.error(msgStack.join('\n'));
};
phantom.onError = function(msg, trace)
{ //Error handling mantra
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
});
}
console.error(msgStack.join('\n'));
phantom.exit(1);
};
function start( url )
{
page.open( url , function (status)
{
console.log( 'Loaded' , url , ': ' , status );
if( status != 'success' )
phantom.exit( 0 );
page.render( 'login.png');
var list = page.evaluate(function() {
return document.getElementsByTagName('a');
});
console.log( 'List length: ' , list.length );
for( var i = 0 ; i < list.length ; i++ )
{
if( !list[i] )
{
console.log( i , typeof list[i] , list[i] === null , list[i] === undefined );
//list[i] === null -> true for the problematic anchors
continue;
}
console.log( i, list[i].innerText , ',' , list[i].text /*, JSON.stringify( list[i] ) */ );
}
//Exit with grace
phantom.exit( 0 );
});
}
start( 'http://data.stackexchange.com/' );
//start( 'http://data.stackexchange.com/account/login?returnurl=/' );
The current version of phantomjs permits only primitive types (boolean, string, number, [] and {}) to pass to and from the page context. So essentially all functions will be stripped and that is what DOM elements are. t.niese found the quote from the docs:
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.
Closures, functions, DOM nodes, etc. will not work!
You need to do a part of the work inside of the page context. If you want the innerText property of every node, then you need to map it to a primitive type first:
var list = page.evaluate(function() {
return Array.prototype.map.call(document.getElementsByTagName('a'), function(a){
return a.innerText;
});
});
console.log(list[0]); // innerText
You can of course map multiple properties at the same time:
return Array.prototype.map.call(document.getElementsByTagName('a'), function(a){
return { text: a.innerText, href: a.href };
});
I have a web crawler and I use phantomjs to parse pages,
I want to get the html, but I always get this type of errors in the output before the html code
ReferenceError: Can't find variable: collapse_content_selector
http://staticloads.com/js/toggle.js?v=2013.10.04:135
TypeError: 'undefined' is not a function (evaluating '$('[placeholder]').placeholderLabel()')
how can I stop that
The easiest way is to add an error handler to phantom.onerror or webpage.onerror.
These callbacks are invoked when there is a JavaScript execution error (in the page or in your script).
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
// uncomment to log into the console
// console.error(msgStack.join('\n'));
};
I need a way to replace part of a string with another string using Google Apps Script. I tested the following and it worked:
function test(){
var value = 'https://plus.google.com/117520727894266469000';
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
function googlePlus(value){
var apiKey = ScriptProperties.getProperty('apiKey');
var re = 'http://'
var theURL = value;
Logger.log('Google+ is called: ' + value);
var replacingItem = 'https://';
var theURL = theURL.replace(re, replacingItem);
Logger.log('Google+ Values 2: ' + value + ' : ' + theURL + ' after ' + replacingItem);
return imageURL;
}
But, when I embedded into the following code, it did not work. Any idea?
//If a Google+ column was not specified,put a flag.
if (googleColumn && column == googleColumn) {
if (value == ""){
columns.push(nogoogleColumn);
values.push(flag);
var googleimageURL="";
} else {
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
}
The script did not work as I wish. It seems to stop at line:
var theURL = theURL.replace(re, replacingItem);
Additional information: Google notified me with the following message
onFormSubmit
TypeError: Cannot find function replace in object https://plus.google.com/117520727894266469000. (line 536) formSubmit
I found the mistake. It is Type Error. value in the second block is not a "string", while the first block is a "string". Hence to fix the second block, I need to use:
var value = value.toString();
before passing to googlePlus(value)
I've got a dropdown menu on my form, which when something is selected I need to reload the current page, but with an appended querystring.
How would I go about doing this?
This is an old question but it came up first in google search results.
The solution I went with is similar to jAndy's.
window.location.pathname gives me the page's url without the query string.
I'm then able to build the query string with "?"+$.param({'foo':'bar','base':'ball'}) which I then append to the pathname and set to window.location.href.
window.location.href = window.location.pathname+"?"+$.param({'foo':'bar','base':'ball'})
var params = [
"foo=bar",
"base=ball"
];
window.location.href =
"http://" +
window.location.host +
window.location.pathname +
'?' + params.join('&');
That code within your change event handler will do the trick.
For instance:
$('#my_dropdown_id').bind('change', function(){
var params = [
"foo=bar",
"base=" + $(this).val()
];
window.location.href = "http://" + window.location.host + window.location.pathname + '?' + params.join('&');
});
If you go with the top rated answer, you may want to replace
http://
in the code with
window.location.protocol
so that it works for other protocols, like https or file. So
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.join('&');
Actually, there a built-in function of location that you can use, the name of the function is assign.
For appending or modifying there is another built-in function of the URL class that you can use too. the name of the function is searchParams.
So for your case you just need below example:
const url = new URL(location.href);
url.searchParams.set('key', 'value');
location.assign(url.search);
Update 2022
I create a TypeScript function to apply redirect with params more easier:
const isClient = (): boolean => typeof window !== 'undefined';
type ParamsType = { [key: string]: string | number };
const redirectUrl = (url: string, params?: ParamsType): void => {
if (isClient()) {
try {
const _url = new URL(url);
if (params) {
const keyList = Object.keys(params);
for (let i = 0; i < keyList.length; i += 1) {
const key = keyList[i];
_url.searchParams.set(keyList[i], params[key]?.toString());
}
}
window.location.assign(_url.href);
} catch (e) {
throw new Error('The URL is not valid');
}
}
};
export default redirectUrl;
If you want a simple way to preserve the query string and possibly append to it, use window.location.search; here's a snippet:
var search = window.location.search + (window.location.search ? "&" : "?");
search += "param1=foo¶m2=bar";
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + search;
You can, of course, use a more sophisticated way of building the rest of your query string, as found in the other examples, but the key is to leverage Location.search.
If you have an existing querystring that you'd like to keep then this version does that and adds your new params to any existing ones. The keys are converted to lowercase so that duplicates are not added. Maintaining the quersytring does make the solution more complicated, so I'd only do this if you need to.
$("#sortby").change(function () {
var queryString = getQueryStrings();
// Add new params to the querystring dictionary
queryString["sortby"] = $("#sortby").val();
window.location.href =
window.location.protocol + "//" +
window.location.host +
window.location.pathname +
createQueryString(queryString);
});
// http://stackoverflow.com/questions/2907482
// Gets Querystring from window.location and converts all keys to lowercase
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0]).toLowerCase()] = decode(key[1]);
}
}
return assoc;
}
function createQueryString(queryDict) {
var queryStringBits = [];
for (var key in queryDict) {
if (queryDict.hasOwnProperty(key)) {
queryStringBits.push(key + "=" + queryDict[key]);
}
}
return queryStringBits.length > 0
? "?" + queryStringBits.join("&")
: "";
}
I was having a requirement to open a particular tab after reloading. So I just needed to append the #tabs-4 to the current url. I know its irrelevant to current post but it could help others who come to this just like I did.
Using the code
window.location = window.location.pathname
+ window.location.search + '#tabs-4';
did'nt work for me but below code did.
location = "#tabs-4";
location.reload(true);