Let's say I have a page called https://randompagename.com, I know I can send GET parameters to this page using this syntax: https://randompagename.com/?parameter1="one"¶meter2="two".
I also know that on a Node.js web app I have an easy way of getting these parameters inside a variable. However, when I'm using pure frontend Javascript without Node.js, I usually solve this problem with something like:
const myURL = decodeURI(window.location.href)
This way, I discover that my page is https://randompagename.com/?parameter1="one"¶meter2="two" and then I can parse it excluding everything after the first = sign and then splitting everything on &. Well, even though this is functional I'm probably missing an easier way of solving this problem. How can I get GET parameters on a page without using any library?
You can use the URL object https://developer.mozilla.org/en-US/docs/Web/API/URL
If the URL of your page is https://example.com/?name=Jonathan%20Smith&age=18 you could parse out the name and age parameters using:
let searchString = (new URL(document.location)).search; //?name=Jonathan%20Smith&age=18
let params = (new URL(document.location)).searchParams;
let name = params.get('name'); // is the string "Jonathan Smith".
let age = parseInt(params.get('age')); // is the number 18
Does anyone have a simple text list or regex of all default JavaScript commands, functions, build-ins and/or keywords?
I am writing an AI to detect malicious web calls. To make it easier for the AI to learn I am pre detecting SQL, Unix etc.
What I have:
const sql_keywords = /(?:alter|begin|create|delete|drop|exec|rollback|update|select)/gi;
const sql_others = /(?:1=1|ALL|AS|ASC|CONCAT|CURRENT|DELAY|DISTINCT|FROM|GROUP|BY|HAVING|WINDOW|UNION|INTERSECT|EXCEPT|ORDER|DESC|USING|NULLS|FIRST|LAST|LIMIT|OFFSET|ROW|ROWS|FETCH|NEXT|ONLY|NO|KEY|SHARE|OF|NOWAIT|LATERAL|NATURAL|TABLE|RETURNING|WAITFOR|WHERE)/gi;
const unix_commands = /\b(?:admin|alias|ar|asa|at|awk|basename|batch|bc|bg|c99|cc|cal|cat|cd|cflow|chgrp|chmod|chown|cksum|cmp|comm|command|compress|cp|crontab|csplit|ctags|cut|cxref|date|dd|delta|df|diff|dirname|du|echo|ed|env|ex|expand|expr|false|fc|fg|file|find|fold|fort77|fuser|gencat|get|getconf|getopts|grep|hash|head|iconv|id|ipcrm|ipcs|jobs|join|kill|lex|link|ln|locale|localedef|logger|logname|lp|ls|m4|mailx|make|man|mesg|mkdir|mkfifo|more|mv|newgrp|nice|nl|nm|nohup|od|paste|patch|pathchk|pax|pr|printf|prs|ps|pwd|qalter|qdel|qhold|qmove|qmsg|qrerun|qrls|qselect|qsig|qstat|qsub|read|renice|rm|rmdel|rmdir|sact|sccs|sed|sh|sleep|sort|split|strings|strip|stty|tabs|tail|talk|tee|test|time|touch|tput|tr|true|tsort|tty|type|ulimit|umask|unalias|uname|uncompress|unexpand|unget|uniq|unlink|uucp|uudecode|uuencode|uustat|uux|val|vi|wait|wc|what|who|write|xargs|yacc|zcat)\b/gi
const unix_others = /\b(?:group|passwd|shadow)\b/gi
const ambiguous = /\b(?:id|nl|crontab|date|file|find)\b/gi
What I want:
const js_commands = /\b(?:alert|...|...|...|...)\b/gi
I ask this question because you can find results for SQL and Unix relatively quickly in Google. For JavaScript, I haven't found anything comparable in a hurry.
It does not have to be complete.
const js_commands = /\b(?:abstract|afterprint|AggregateError|alert|animationcancel|animationend|animationiteration|animationstart|arguments|Array|ArrayBuffer|async|AsyncFunction|AsyncGenerator|AsyncGeneratorFunction|Atomics|await|beforeprint|beforeunload|BigInt|BigInt64Array|BigUint64Array|Block|blur|Boolean|boolean|break|byte|cancelAnimationFrame|cancelIdleCallback|case|catch|char|class|clearImmediate|clipboardchange|close|confirm|const|continue|convertPointFromNodeToPage|convertPointFromPageToNode|copy|copy_event.clipboardData|crypto|customElements|cut|cut_event.clipboardData|DataView|Date|debugger|decodeURI|decodeURIComponent|default|delete|devicemotion|deviceorientation|devicePixelRatio|dialogArguments|do|document|DOMContentLoaded|double|each|else|Empty|encodeURI|encodeURIComponent|enum|error|eval|EvalError|event|export|extends|external|false|final|finally|find|float|Float32Array|Float64Array|focus|for|frameElement|frames|fullScreen|function|gamepadconnected|gamepaddisconnected|Generator|GeneratorFunction|get|getAttention|getAttentionWithCycleCount|getComputedStyle|getDefaultComputedStyle|getSelection|globalStorage|globalThis|goto|hashchange|history|home|if|implements|import|import.meta|in|Infinity|innerHeight|innerWidth|instanceof|int|Int16Array|Int32Array|Int8Array|interface|InternalError|Intl|Intl.Collator|Intl.DateTimeFormat|Intl.DisplayNames|Intl.ListFormat|Intl.Locale|Intl.NumberFormat|Intl.PluralRules|Intl.RelativeTimeFormat|isFinite|isNaN|isSecureContext|JSON|label|languagechange|length|let|load|localStorage|location|locationbar|long|Map|matchMedia|Math|maximize|menubar|message|messageerror|minimize|moveBy|moveTo|mozAnimationStartTime|mozInnerScreenX|mozInnerScreenY|mozPaintCount|name|NaN|native|navigator|new|null|Number|Object|of|offline|onappinstalled|onbeforeinstallprompt|ondevicelight|ondevicemotion|ondeviceorientation|ondeviceorientationabsolute|ondeviceproximity|ongamepadconnected|ongamepaddisconnected|online|onorientationchange|onpaint|onuserproximity|onvrdisplayactivate|onvrdisplayblur|onvrdisplayconnect|onvrdisplaydeactivate|onvrdisplaydisconnect|onvrdisplayfocus|onvrdisplaypointerrestricted|onvrdisplaypointerunrestricted|onvrdisplaypresentchange|open|openDialog|opener|orientation|orientationchange|origin|outerHeight|outerWidth|OverconstrainedError|package|pagehide|pageshow|pageXOffset|pageYOffset|parent|parseFloat|parseInt|paste|paste_event.clipboardData|performance|personalbar|pkcs11|popstate|postMessage|preventDefault|print|private|Promise|prompt|Proxy|public|RangeError|ReferenceError|Reflect|RegExp|rejectionhandled|requestAnimationFrame|requestFileSystem|requestIdleCallback|resize|resizeBy|resizeTo|resolveLocalFileSystemURL|return|returnValue|routeEvent|screen|screenLeft|screenTop|screenX|screenY|scroll|scrollbars|scrollBy|scrollByLines|scrollByPages|scrollMaxX|scrollMaxY|scrollTo|ScrollToOptions|scrollX|scrollY|self|sessionStorage|set|Set|setCursor|setImmediate|setResizable|SharedArrayBuffer|short|showModalDialog|sizeToContent|speechSynthesis|static|status|statusbar|stop|storage|String|super|switch|Symbol|synchronized|SyntaxError|target|this|throw|throws|toolbar|top|transfer|transient|transitioncancel|transitionend|transitionrun|transitionstart|true|try|TypeError|typeof|Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|undefined|unhandledrejection|unload|updateCommands|URIError|value|var|visualViewport|void|volatile|vrdisplayactivate|vrdisplayblur|vrdisplayconnect|vrdisplaydeactivate|vrdisplaydisconnect|vrdisplayfocus|vrdisplaypointerrestricted|vrdisplaypointerunrestricted|vrdisplaypresentchange|WeakMap|WeakSet|WebAssembly|WebAssembly.CompileError|WebAssembly.Instance|WebAssembly.LinkError|WebAssembly.Memory|WebAssembly.Module|WebAssembly.RuntimeError|WebAssembly.Table|while|window|with|yield)\b/gi
Sources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar
https://developer.mozilla.org/en-US/docs/Web/API/Window
Please comment if you find a missing default JS command, function, built-in (I am only interested in key "words").
I currently have a function to take a string, break it up into sentences, then extract the sentences that contain a user defined keyword and return them:
function getSentencesWithWord(word, text) {
let sentenceArray = text.replace(/([.])\s*(?=[A-Z])/g, "$1|").split("|")
return sentenceArray.filter(sentence => sentence.includes(word))
}
Currently, this function works. However, the amount of text I need to search through with this function is quite large; it is searching through around 30 google docs that could each be up to 75 pages each, and searching for certain terms (such as the word "the") can take up to a minute for the function to complete. Is there a more optimized way to search through and extract this much text?
Edit:
Because someone asked in the comments, the word variable is just a string obtained from a text input on an HTML page and the text variable is a string obtained via this function in a Google Apps Script:
function getText(docID){
let doc = DocumentApp.openById(docID);
let textToSearch = doc.getBody().getText();
return textToSearch;
}
I have an array of all the google doc IDs I need to access and I just iterate over the array and obtain the text for each doc
The replace you've provided, replace(/([.])\s*(?=[A-Z])/g, "$1|"), didn't work for me == got the same string without change...
How about this:
("|"+text.toLowerCase().replace(/\s/g, "|")+"|").includes("|"+word.toLowerCase()+"|")
Or, this:
("|"+text.toLowerCase().split(" ").join("|")+"|").includes("|"+word.toLowerCase()+"|")
Was unable to find a faster method of achieving this with Google Apps Script so I just went back to Node.js and ended up using the Google Drive API to download the files as .txt files, which are much smaller and so I can search through them much faster now
I'm writing a script on Google Script to interact with the Airtable's API.
To ask the API to return a list of records based in a query, they provide the URL to send the post request. However, for the query part of the Url they ask to translate special characters to HTML.
Straight to my question: Is there any cleaner way to code this?
My first solution was to create a dictionary for each character, then run a "replace" method to substitute the special characters to the relative ones on the dictionary.
Any person with a bit more knowledge in Javascript than me? Remembering that I'm running this on Google Scripts.
function urlEncoder(toEncode) {
var dictionary = {
'(':'(',')':')','`':'%60','~':'~','!':'!','#':'%40','#':'%23','^':'%5E','$':'%24','%':'%25','&':'%26',
'*':'*','-':'-','_':'_','=':'%3D','+':'%2B','[':'%5B',']':'%5D','{':'%7B','}':'%7D','\\':'%5C','|':'%7C',';':'%3B',':':':',
'\'':'\'','\"':'\"',',':'%2C','<':'%3C','.':'.','>':'%3E','/':'%2F','?':'%3F',' ':'+',
'à':'%C3%A0','À':'%C3%80','á':'%C3%A1','Á':'%C3%81','â':'%C3%A2','Â':'%C3%82','ä':'%C3%A4','Ä':'%C3%84','ã':'%C3%A3','Ã':'%C3%83',
'è':'%C3%A8','È':'%C3%88','é':'%C3%A9','É':'%C3%89','ê':'%C3%AA','Ê':'%C3%8A','ë':'%C3%AB','Ë':'%C3%8B',
'ì':'%C3%AC','Ì':'%C3%8C','í':'%C3%AD','Í':'%C3%8D',
'ò':'%C3%B2','Ò':'%C3%92','ó':'%C3%B3','Ó':'%C3%93','ô':'%C3%B4','Ô':'%C3%94','ö':'%C3%B6','Ö':'%C3%96','õ':'%C3%B5','Õ':'%C3%95',
'ù':'%C3%B9','Ù':'%C3%99','ú':'%C3%BA','Ú':'%C3%9A','û':'%C3%BB','Û':'%C3%9B','ü':'%C3%BC','Ü':'%C3%9C',
'ç':'%C3%A7','Ç':'%C3%87','ñ':'%C3%B1','Ñ':'%C3%91'
}
var result = toEncode.replace(/[^a-z0-9]/gi, m => dictionary[m])
Logger.log('URL Encoder:'+toEncode+'>>'+result)
return result
}
The string encoder provided by Airtable can be found here: https://codepen.io/airtable/full/rLKkYB
Thanks!
There is no need to make your own function for that, there's already a function called encodeURI in javascript:
var url = "my test.asp?name=ståle&car=saab";
var res = encodeURI(url);
// res = "my%20test.asp?name=st%C3%A5le&car=saab"
I am using the new method: Utilities.formatString()
In the Google Documentation is says it is similar to sprintf %-style.
I searched and read this article about sprintf in PHP.
I cannot seem to get this to work as intended. It is meant to pad this 8 character string with 4 leading zeros. I know there are other ways to do this, But I am trying to get a handle on this sprintf / formatString thing.
var noFormat = "12345678";
var formatted = Utilities.formatString("%012s", noFormat);
I expected the var formatted to be equal to "000012345678".
my debugger tell me that formatted = 0, or sometimes it throws an error..
I am confused.
try it like this :
function xxx(){
var noFormat = '12345678'
var formatted = Utilities.formatString("%012d", noFormat);
Logger.log(formatted)
}
the different parameters that can be used are easy to find on the web, here is an example that explains how the argument must be evaluated in php but the usage is the same.
Logger result :