Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Javascript statement (regular expression) mean?

What does the RegEx test for here?

function chksql(){    
  if (/^\s*(?:delete|drop|truncate|alter)/.test(v)) return false;    
}

I just know it's mixed with regular expression, but can't figure out what it means.

like image 217
just_a_newbie Avatar asked Oct 03 '13 04:10

just_a_newbie


2 Answers

it means its checking if v is a string that starts with zero or more white space charcters followed by delete or drop or truncate or alter

so if v were " alter" this would return false.

see docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

I should add that checking against this happening on the client side is a really bad idea. It will be circumvented.

like image 169
mkoryak Avatar answered Oct 12 '22 12:10

mkoryak


There are a number of good online tools for testing and exploring regular expressions these days.

One I like is debuggex.com. Here's what it displays for your regular expression:

^\s*(?:delete|drop|truncate|alter)

Regular expression visualization

Debuggex Demo

To interpret that, you still need to do a bit of homework like finding out what ^ and \s mean, but the "railroad diagram" helps show what the regular expression is testing for. Just follow the lines to see what it will match. You can also try typing in test strings at the link above to see how it matches (or doesn't match) them.

Another good site is regex101.com. Here's your regular expression there. They give you an English description of what the regular expression is looking for.

Also, heed mkoryak's advice about trying to sanitize SQL on the client!

enter image description here

like image 2
Michael Geary Avatar answered Oct 12 '22 13:10

Michael Geary