Unable to query postgres db with _ using javascript - javascript

I'm trouble shooting this application that I ave had no hand in creating, but I get to fix. Anywho, I'm finding that I am unable to query the postgres db for any variable that has an _. Now before you say use escape characters, I've already been there, done that, and got the t-shirt. From what I could tell, the application uses escape-string-regexp module to alter the string, for example => "some_random#email.com" => "some_random#email\.com" I added my own module to single out the _ and now the output is => "some\\_random#email\.com". Note the two escapes for the underscore as prescribed by the mass forums that I have scaled. I even built a tool to test out in python and that works. Slightly different as I use => "(E'some\\_random#email\\.com')". Tried that with javascript as well and still no dice. What say all ye? Oh, this shoots out via expressjs from what I can tell. I'm not a javascript guy.

Found the solution. I and another team mate went back and revisited the method I created and changed the " to '. Next thing you know, it started working.
exports.stringChanger = function(word){
//console.log(word)
var metas = ["_"];
var guestPool = word.split("");
//console.log(guestPool)
for(i in range(guestPool.length)){
for(j in range(metas.length)){
if(guestPool[i] === metas[j]){
guestPool[i] = "\\" + guestPool[i];
}
}
}
var guest = guestPool.join("");
return guest;
//console.log(guest)
};
to
exports.stringChanger = function(word){
//console.log(word)
var metas = ['_'];
var guestPool = word.split("");
//console.log(guestPool)
for(i in range(guestPool.length)){
for(j in range(metas.length)){
if(guestPool[i] === metas[j]){
guestPool[i] = '\\' + guestPool[i];
}
}
}
var guest = guestPool.join("");
return guest;
//console.log(guest)
};

Related

Javascipt replacing exact numbers in an array

am trying to replace numbers in an array but am facing an issue which am not really able to correctly manage regarding how to correctly target the just one data I really have to change.
I'll make an example to have more accuracy on describing it.
Imagine my data array look like that:
["data", "phone numbers", "address"]
I can change numbers via following script but my first problem is that it makes no differences between the number it find in columns, for example "phone numbers" from "address" (at the moment am not using it, but should I include a ZIP code in the address it would be really be a problem)
Beside, my second and current problem with my script, is that obviosuly in the same "phone numnbers" a number may appear more times while I'd like to affect only the first block of the data - let's say to add/remove the country code (or even replace it with it's country vexillum) which I normally have like that "+1 0000000000" or "+54 0000000000"
So if a number is for example located in EU it really make this script useless: Spain is using "+34" while France "+33" and it wouldn't succeded in any case becouse it recognize only "+3" for both.
I've found some one else already facing this problems which seems to solved it wrapping the values inside a buondaries - for example like that "\b"constant"\b" - but either am wronging syntax either it does not really apply to my case. Others suggest to use forEach or Array.prototype.every which I failed to understand how to apply at this case.
Should you have other ideas about that am open to try it!
function phoneUPDATES(val)
{
var i= 0;
var array3 = val.value.split("\n");
for ( i = 0; i < array3.length; ++i) {
array3[i] = "+" + array3[i];
}
var arrayLINES = array3.join("\n");
const zero = "0";
const replaceZERO = "0";
const one = "1";
const replaceONE = "1";
const result0 = arrayLINES.replaceAll(zero, replaceZERO);
const result1 = result0.replaceAll(one, replaceONE);
const result2 = result1.replaceAll(two, replaceTWO);
const result3 = result2.replaceAll(thre, replaceTHREE);
const result4 = result3.replaceAll(four, replaceFOUR);
const result5 = result4.replaceAll(five, replaceFIVE);
const result6 = result5.replaceAll(six, replaceSIX);
const result7 = result6.replaceAll(seven, replaceSEVEN);
const result8 = result7.replaceAll(eight, replaceEIGHT);
const result9 = result8.replaceAll(nine, replaceNINE);
const result10 = result9.replaceAll(ten, replaceTEN);
const result11 = result10.replaceAll(eleven, replaceELEVEN);
Why not use a regex replace, you could do something like /(\+\d+ )/g which will find a + followed by one or more digits followed by a space, and then you can strip out the match:
const phoneNumbers = [, "+54 9876543210"]
console.log(phoneNumbers.map((num) => num.replaceAll(/(\+\d+ )/g, '')))
If you need to only target the second element in an array, i'd imagine your data looks like
const data = [["data", "+1 1234567890, +1 5555555555", "address"], ["data", "+11 111111111, +23 23232323", "address"]];
console.log(data.map((el) => {
el[1] = el[1].replaceAll(/(\+\d+ )/g, '');
return el;
}))
ok, this almost is cheating but I really didn't thought it before and, by the way does, not even actually solve the problems but jsut seems to work around it.
If I call the replacemente in decreasing order that problem just does not show up becouse condition of replacement involving higher numbers are matched before the smaller one.
but should some one suggest a complete "true code comply" solution is wellcome

Website Interference w/ Multiple Instances Running (JavaScript)

I am relatively new to JavaScript but I am creating a simple hangman web app in local host. The game runs perfectly, just as I want it. However, I realized that after loading the game at the same time in different tabs, the words change in all instances to the same word. For example, I can run the game in one tab, then another. Then when I go back to the first tab, the word I am trying to guess has changed to the one in the second tab. I don't know how else to describe my issue. Here's my JS and backend code:
JS
function runHangmanInit(){
$.get("/hangmanInit", {}, function(response){ //generates word
term.write("RUNNING HANGMAN.cpp\r\n");
guessedLetters = [];
let json = JSON.parse(response);
console.log(json);
term.write(json["state"] + "\r\n");
term.write("Category: " + json["category"] + "\t");
for(let i = 0; i < json["dashes"]; i++){
term.write(" _");
}
term.write("\r\nGuesses remiaining: "+ json["guesses"] + "\r\n");
term.write(json["message"]);
});
}
function checkLetterTerminal(letter){
$.get("/hangman/" + letter, {}, function(response){
let x = JSON.parse(response);
//console.log(x);
if(x["err"]){
term.write(x["err"]);
}
else{
term.write(x["state"] + "\r\n");
term.write("Category: " + x["category"] + "\t");
for(let i = 0; i < x.dashes.length; i++){
term.write(x.dashes[i] + " ");
}
term.write("\r\nGuesses remiaining: "+ x["guesses"] + "\r\n");
if(x["lettersGuessed"]){ //Incorrect guess
guessedLetters.push(x["lettersGuessed"]);
}
term.write("Letters Guessed: ");
for(let i = 0; i < guessedLetters.length; i++){
term.write(guessedLetters[i] + " ");
}
term.write("\r\n");
}
if(x["message"]){
term.write(x["message"] + "\r\n");
check1 = 0;
term.write("\r\n\x1B[1;3;31mdyaranon#DEKTOP-123:\x1B[0m/mnt/e$ ");
}
else{
term.write("\r\nEnter your guess: ");
}
});
}
Backend (Crow C++)
int main(int argc, char* argv[]){
crow::SimpleApp app;
Game game = Game(1);
CROW_ROUTE(app, "/hangmanInit")([](const request& req, response& res){
nlohmann::json x;
game.init();
x["word"] = game.getWord();
x["state"] = game.board.hangman;
x["category"] = game.categoryName;
x["dashes"] = game.board.dashes.size();
x["guesses"] = 6;
x["message"] = "Enter your guess: ";
res.sendJSON(x);
});
CROW_ROUTE(app, "/hangman/<string>")([](const request &req, response &res, string letter){
nlohmann::json x;
x = game.playGame(letter);
res.sendJSON(x);
});
I included all the relative parts of the code. Any help would be appreciated.
It looks like you're only creating one game instance? So yes, there's only once instance server-side and you're sharing it among all clients.
HTTP is stateless, so you first need a way to identify which client is which when they make requests. This is normally done by a session ID of some sort, which should be randomly generated.
It's common to store this session ID in cookies, but you'll actually want to just use a local variable in your JavaScript when the page loads, since you want to treat each tab differently.
From there, when you make your HTTP requests (which you're doing with $.get()), you need to include this session ID. I suggest putting it in the URL, something like:
/hangman/<some-game-id-here>/<some-route>
Finally, on the server side, you need to track multiple game instances... one for each game going on, and associate them with the session IDs.

javascript to parse csv excel file

I am trying to parse a CSV file I made in Excel. I want to use it to update my Google map. This Google map is in a mobile app that I am developing with Eclipse for Android.
Honestly, I am not sure how to write the JavaScript. Any help will be greatly appreciated. I would be happy to credit your work.
I just want some JavaScript to run when the user hits a button that does the following:
Locates users current location (I have already done this part!)
Locate nearby locations as entered in the .CSV excel file by parsing the .CSV
Display a small link inside every locations notification bubble that says "Navigate" that when the user clicks it, opens google maps app and starts navigating the user to that location from the users current location (Geolocation).
This is the ONLY part I need to finish this application. So once again, any help at all will be greatly appreciated. Thanks everyone!
Honestly, I've been round and round with this problem. The CSV format is not made for easy parsing and even with complicated RegEx it is difficult to parse.
Honestly, the best thing to do is import it into an FormSite or PHPMyAdmin, then re-export the document with a custom separator that is easier to parse than ",". I often use "%%" as the field delimiter and everything works like a charm.
Dont know if this will help but see http://www.randomactsofsentience.com/2012/04/csv-handling-in-javascript.html if it helps...
Additional:
On top of the solution linked to above (my preference) I also used a shed load of stacked regular expressions to token a CSV but it's not as easy to modify for custom error states...
Looks heavy but still only takes milliseconds:
function csvSplit(csv){
csv = csv.replace(/\r\n/g,'\n')
var rows = csv.split("\n");
for (var i=0; i<rows.length; i++){
var row = rows[i];
rows[i] = new Array();
row = row.replace(/&/g, "&");
row = row.replace(/\\\\/g, "\");
row = row.replace(/\\"/g, """);
row = row.replace(/\\'/g, "'");
row = row.replace(/\\,/g, ",");
row = row.replace(/#/g, "#");
row = row.replace(/\?/g, "?");
row = row.replace(/"([^"]*)"/g, "#$1\?");
while (row.match(/#([^\?]*),([^\?]*)\?/)){
row = row.replace(/#([^\?]*),([^\?]*)\?/g, "#$1,$2?");
}
row = row.replace(/[\?#]/g, "");
row = row.replace(/\'([^\']*)\'/g, "#$1\?");
while (row.match(/#([^\?]*),([^\?]*)\?/)){
row = row.replace(/#([^\?]*),([^\?]*)\?/g, "#$1,$2?");
}
row = row.replace(/[\?#]/g, "");
row = row.split(",")
for (var j=0; j<row.length; j++){
col = row[j];
col = col.replace(/?/g, "\?");
col = col.replace(/#/g, "#");
col = col.replace(/,/g, ",");
col = col.replace(/'/g, '\'');
col = col.replace(/"/g, '\"');
col = col.replace(/\/g, '\\');
col = col.replace(/&/g, "&");
row[j]=col;
}
rows[i] = row;
}
return rows;
}
I had this problem which is why I had to come up with this answer, I found on npm a something called masala parser which is indeed a parser combinator. However it didn't run on browsers yet, which is why I am using this fork, the code remains unchanged. Please read it's documentation to understand the Parser-side of the code.
import ('https://cdn.statically.io/gh/kreijstal-contributions/masala-parser/Kreijstal-patch-1/src/lib/index.js').then(({
C,
N,
F,
Streams
}) => {
var CSV = (delimeter, eol) => {
//parses anything beween a string converts "" into "
var innerstring = F.try(C.string('""').returns("\"")).or(C.notChar("\"")).rep().map(a => a.value.join(''));
//allow a string or any token except line delimeter or tabulator delimeter
var attempth = F.try(C.char('"').drop().then(innerstring).then(C.char('"').drop())).or(C.charNotIn(eol[0] + delimeter))
//this is merely just a CSV header entry or the last value of a CSV line (newlines not allowed)
var wordh = attempth.optrep().map(a => (a.value.join('')));
//This parses the whole header
var header = wordh.then(C.char(delimeter).drop().then(wordh).optrep()).map(x => {
x.header = x.value;
return x
})
//allow a string or any token except a tabulator delimeter, the reason why we allow newlines is because we already know how many columns there is, so if there is a newline, it is part of the value.
var attempt = F.try(C.char('"').drop().then(innerstring.opt().map(a=>(a.value.__MASALA_EMPTY__?{value:""}:a))).then(C.char('"').drop())).or(C.notChar(delimeter))
//this is merely just a CSV entry
var word = attempt.optrep().map(a => (a.value[0]?.value??a.value[0]));
//This parses a CSV "line" it will skip newlines if they're enclosed with doublequotation marks
var line = i => C.string(eol).drop().then(word.then(C.char(delimeter).drop().then(word).occurrence(i - 1).then(C.char(delimeter).drop().then(wordh)))).map(a => a.value);
return header.flatMap(a => line(a.header.length - 1).rep().map(b => {
b.header = a.header;
return b
}))
};
var m = {
'tab': '\t',
"comma": ",",
"space": " ",
"semicolon": ";"
}
document.getElementById('button').addEventListener('click', function() {
var val = document.getElementById('csv').value;
var parsedCSV = CSV(m[document.getElementById('delimeter').value], '\n').parse(Streams.ofString(val)).value;
console.log(parsedCSV);
})
})
Type some csv<br>
<textarea id="csv"></textarea>
<label for="delimeter">Choose a delimeter:</label>
<select name="delimeter" id="delimeter">
<option value="comma">,</option>
<option value="tab">\t</option>
<option value="space"> </option>
<option value="semicolon">;</option>
</select>
<button id="button">parse</button>
I would suggest stripping the newlines and the end of the file. Because it might get confused.
This appears to work. You may want to translate the Japanese, but it is very straight-forward to use:
http://code.google.com/p/csvdatajs/

Url parsing in javascript and DOM

I am writing a support chat application where I want text to be parsed for urls. I have found answers for similar questions but nothing for the following.
what i have
function ReplaceUrlToAnchors(text) {
var exp = /(\b(https?:\/\/|ftp:\/\/|file:\/\/|www.)
[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1' target='_blank'>$1</a>");
}
that pattern is a modified version of one i found on the internet. It includes www. in the first token, because not all urls start with protocol:// However, when www.google.com is replaced with
<a href='www.google.com' target='_blank'>www.google.com</a>
which pulls up MySite.com/webchat/wwww.google.com and I get a 404
that is my first problem, my second is...
in my script for generating messages to the log, I am forced to do it a hacky way:
var last = 0;
function UpdateChatWindow(msgArray) {
var chat = $get("MessageLog");
for (var i = 0; i < msgArray.length; i++) {
var element = document.createElement("div");
var linkified = ReplaceUrlToAnchors(msgArray[i]);
element.setAttribute("id", last.toString());
element.innerHTML = linkified;
chat.appendChild(element);
last = last + 1;
}
}
To get the "linkified" string to render HTML out correctly I have to use the non-standard .innerHTML attribute of element. I would prefer a way were i could parse the string as tokens - text tokens and anchor tokens - and call either createTextNode or createElement("a") and stitch them together with DOM.
so question 1 is how should I go about www.site.com parsing, or even site.com?
and question 2 is how would could I do this using only DOM?
Another thing you could do is this:
function ReplaceUrlToAnchors(text) {
var exp = /(\b(https?:\/\/|ftp:\/\/|file:\/\/|www.)
[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp, function(_, url) {
return '<a href="' +
(/^www\./.test(url) ? "http://" + url : url) +
'target="_blank">' +
url +
'</a>';
});
}
That is kind-of like your solution, but it does the check for "www" URLs in that callback passed in to ".replace()".
Note that you won't be picking up "stackoverflow.com" or "newegg.com" or anything like that, which I understand may be unavoidable (and even desirable, given the false positives you'd pick up).
Here is what I came up with, perhaps someone has something better?
function replaceUrlToAnchors(text) {
var naked = /(\b(www.)[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|](.com|.net|.org|.co.uk|.ca|.))/ig;
text = text.replace(naked, "http://$1");
var exp = /(\b(https?:\/\/|ftp:\/\/|file:\/\/)([-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|]))/ig;
return text.replace(exp,"<a href='$1' target='_blank'>$3</a>");
}
the first regex will replace www.google.com with http://www.google.com and is good enough for what I am doing. However, I will hold off marking this as the answer because I would also like to make (www.) optional but when I do (www.)? it replaces every word with http://word/

Javascript Regular Expression to attempt to split name into Title/First Name(s)/Last Name

I want to try and detect the different parts of a person's name in Javascript, and cut them out so that I can pass them onto something else.
Names can appear in any format - for example:-
miss victoria m j laing
Miss Victoria C J Long
Bob Smith
Fred
Mr Davis
I want to try and write something simple, that'll do it's best to guess these and get them right 80% of the time or so (We have some extremely dodgy data)
I'm thinking of something along the lines of using a regex to check whether it has a prefix, then branch off to two places as to whether it has
/^(Dr|Mr|Mrs|Miss|Master|etc).? /
And then cutting the rest of it out using something like
/(\w+ )+(\w+)/
To match last name and other names. Though, I'm unsure on my greedy/ungreedy options here, and whether I can do soemthing to shortcut having all the different paths that might be available. Basically, hoping to find something simple, that does the job in a nice way.
It's also got to be written in Javascript, due to the limitations of the ETL tool I'm using.
Why not split() and just check the resulting parts:
// Split on each space character
var name = "Miss Victoria C J Long".split(" ");
// Check the first part for a title/prefix
if (/^(?:Dr|Mr|Mrs|Miss|Master|etc)\.?$/.test(name[0])) {
name.shift();
}
// Now you can access each part of the name as an array
console.log(name);
//-> Victoria,C,J,Long
Working Demo: http://jsfiddle.net/AndyE/p9ra4/
Of course, this won't work around those other issues people have mentioned in the comments, but you'd struggle on those issues even more with a single regex.
var title = '';
var first_name = '';
var last_name = '';
var has_title = false;
if (name != null)
{
var new_name = name.split(" ");
// Check the first part for a title/prefix
if (/^(?:Dr|Mr|Mrs|Miss|Master)\.?$/i.test(new_name[0]))
{
title = new_name.shift();
has_title = true;
}
if (new_name.length > 1)
{
last_name = new_name.pop();
first_name = new_name.join(" ");
}
else if(has_title)
{
last_name = new_name.pop();
}
else
{
first_name = new_name.pop();
}
}
Adapted from Accepted Answer :)

Categories