I am writing a tutorial page for JavaScript and to prevent xss I want to check if the user's input contains any ajax and if it does return an error string. Also any other elements that could be used for xss in the input should make it error. What would the code for this be?
Try defining a RegExp including methods, strings which should not pass validation , utilize RegExp.prototype.test() with string as argument
var re = /XMLHttpRequest|.\.ajax|.\.get|.\.post|.\.getScript|script/;
var str = "$.post";
var res = re.test(str) ? new Error("error") : str;
console.log(res)
Related
Is there a way to stop inserting an undefined value in MYSQL using reactjs?
so here is the code.
const regex = /.*([A-Za-z0-9_\-]{11}).*/gi;
if (postData.video_id) {
postData.video_id = postData.video_id.replace(regex, "$1");
}
and it keeps submitting undefined in the database, I need to make it optional either with value or empty, it is up to the user.
appreciate your help
the data might do not match with the regex, so
validate the replace expression before assign it to postData.video_id :
const regex = /.*([A-Za-z0-9_\-]{11}).*/gi;
if (postData.video_id) {
const videoId = postData.video_id.replace(regex, "$1");
if(videoId) postData.video_id = videoId;
}
This should be very simple (when you know the answer). From this question
I want to give the posted solution a try. My question is:
How to get the parameter value of a given URL using JavaScript regular expressions?
I have:
http://www.youtube.com/watch?v=Ahg6qcgoay4
I need:
Ahg6qcgoay4
I tried:
http://www.youtube.com/watch\\?v=(w{11})
But: I suck...
You almost had it, just need to escape special regex chars:
regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;
url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'
Edit: Fix for regex by soupagain.
Why dont you take the string and split it
Example on the url
var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"
you can do a split as
var params = url.split("?")[1].split("&");
You will get array of strings with params as name value pairs with "=" as the delimiter.
Not tested but this should work:
/\?v=([a-z0-9\-]+)\&?/i
v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk
In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString
HttpUtility.ParseQueryString(url)["v"];
And you don't even need to check the key, as it will return null if the key is not in the collection.
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
DEMO
I use seperate custom functions which gets all URL Parameters and URL parts .
For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The above function will return an array consisting of url variables.
For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b
I use a simple uri split,
function getUrlParams() {
var vars = {};
var parts = window.location.href.split('/' );
return parts;
}
You can even combine them both to be able to use with a single call in a page or in javascript.
I want to take a value from an URL an put it on an input.
So,
Normal URL: www.mysite.com
URL with value: www.mysite.com/mypage.php?variabletext
So, I want to extract ?variabletext (and, yes, it´s always a different text string)
I´m using this function
$(document).ready(function(){
var urlpage = window.location.href;
regex = /http\:\/\/www\.mysite\.com\/mypage.php\?([a-zA-Z]+)/;
var texturl = urlpage.match(regex)[1];
if(texturl !== null)
{
document.getElementById('idmyinput').value= texturl;
}
});
Now the problem.
If i put a value, for example, www.mysite.com/mypage.php?bob
It works well.
But if it´s not a value, example, www.mysite.com/mypage.php
I receive this error:
TyperError: urlpage.match(...) is null
My idea is that only change the value of the input if the variable texturl has a value, aka, is not null.
Anyone can help me...?
Thanks a lot
If urlpage.match(regex) is null (that is, there is no match), then urlpage.match(regex)[1] will throw.
So you can use
var match = urlpage.match(regex);
if(match) {
var texturl = match[1];
// Use texturl
}
However, parsing URLs manually is a bad idea, use a URLUtils property instead. In this case, search:
The URLUtils.search property is a DOMString containing a ?
followed by the parameters of the URL.
So you can use
var texturl = location.sarch.substr(1);
str =str.replace(/[^a-zA-Z0-9]/g,"");
str = str.replace(/httpwwwmysitecommypagephp/g,"");
I would like to build my own translation function in javascript.
I already have a function language.lookup(key) which translates a word or expression:
var frenchHello = language.lookup('hello') //'bonjour'
Now I would like to write a function which takes a html string and translates it with my lookup function. In the html string I will have a special syntax for example #[translationkey] that will point out that this word should be translated.
This is the result I want:
var html = '<div><span>#[hello]</span><span>#[sir]</span>'
language.translate(html) //'<div><span>bonjour</span><span>monsieur</span>
How would I write language.translate?
My idea is to filter out my special syntax with regex and then run language.lookup on each key. Maybe with string replace or something.
I suck when it comes to regex and I've only come up with a very incomplete example but I include it anyway so maybe someone get the idea of what I am trying to do. Then if there is a better but complete different solution that is more than welcome.
var value = "#[hello], nice to see you.";
lookup = function(word){
return "bonjour";
};
var res = new RegExp( "\\b(hello)\\b", "gi" ).exec(value)
for (var c1 = 0; c1 < res.length; c1++){
value = value.replace(res[c1], lookup(res[c1]))
}
alert(value) //#[bonjour], nice to see you.
The regex should of course not filter out the word hello but the syntax and then collect the key by grouping or similar.
Can anyone help?
Just use String.replace method's ability to call function specified as second argument to generate replacement text and make a global replace using regexp matching your syntax:
var value = "#[hello], #[sir], nice to see you.";
lookup = function(full_match, word){
if(word == 'hello')
return "bonjour";
if(word == 'sir')
return "monsieur"
};
console.log(value.replace(/#\[(.+?)\]/gi, lookup))
Result:
bonjour, monsieur, nice to see you.
Of course when your replacement list gets bigger, you'd better use lookup object instead of series of ifs in lookup function, but you can really do whatever you want there.
You can try this to find all occurrences:
var re = new RegExp('#\\[([^\\]]+?)\\]', 'gi'),
str = '#[value1] plain text #[value2]',
match;
while (match = re.exec(str)) {
console.log(match);
}
You could use something like:
#\\[[^\\]]*\\]
Which matches the hash followed by an opening square bracket followed by zero or more characters NOT including the closing square bracket, followed by a closed square bracket.
Alternatively, perhaps it would be better to handle the translation at the server side (maybe even through your template engine) and send back to your client the translated response. Otherwise, (depending on the specific problem you are dealing with of course), you might end up sending a lot of data to the browser which might make your application respond slowly.
EDIT:
Here is a working piece of code:
var q="This #[ANIMAL1] was eaten by that #[ANIMAL2]";
var u = {"#[ANIMAL1]":"Lion","#[ANIMAL2]":"Frog"};
function insertAnimal(aString, lookup){
var res = (new RegExp("#\\[[^\\]]*\\]", "gi"))
while (m = res.exec(aString)){
aString = aString.replace(m, lookup[m])
}
return aString;
}
function main(){
alert(insertAnimal(q,u));
}
You can call the "main()" from an HTML document's body onload event
I can compare your requirement to 'resolving template texts within content'. If it is feasible to use Jquery , you should try Handlebars.js
.
In JScript, why do I get the error "Object doesn't support this property or method" when I try to convert request.querystring to a string using toString()?
var params = Request.QueryString;
var params = params.toString();
Background info:
I'm trying to convert the querystring to a string so that I can perform a regex replace and remove certain items when they appear in the url.
var param = param.replace(/([?&])(allow)=[\w-]+/g, "");
I recently discovered the solution to this problem.
var params = Request.QueryString;
should be:
var params = Request.QueryString.Item;
There is no need to convert params to a string after that to manipulate the query string. Further you have access to everything in the query string by calling Request.QueryString("param").Item.
Example:
http://www.mysite.com?q=query&name=george
var name = Request.QueryString("name").Item;
I don't know -- weird Microsoft JScript implementation.
I had the same problem.
var strParams = new String(params);
seems to work though.