I have a project, where user can put in drop-down values that can be selected. One can select multiple values at a time. So, we have to store the selection and get it on edit mode.
First thought
Let's store them as comma separated in DB.
f.e.
If suggestions are A , B , C and user selects A and B, I was going to store A,B in DB and while getting back the value split it with comma.
Problem arises when user has genuine "comma" in the field, for an instance first,option & second,option. At that time joining with comma won't work.
Second thought
I can think of another option to store it in a stringified array format and parse it while getting back.
For the above instance, it would store the data as ["first,option","second,option"]. It seems to be a good (and only) option for me.
Even though I have a bit of hesitation doing so (which lead me questioning here!) because my users can access the api/DB value directly and for them it doesn't look good.
So, Is there any other way to address this issue to benefit both parties, developers and users? Thanks in advance!!
I'd suggest using a standardized format such as JSON, XML etc.
Serialize and parse and with a widely used library so all escaping of reserved / special characters is done for you. Rolling your own here will cause you problems!
Better yet, use different fields for each suggestion, this is a better design in general. As long as the number of potential fields is finite this will work, e.g. 1-10 suggestions.
If you're going down the JSON route, we can do this in JavaScript like this:
let suggestions = ['Choice A, commas are not, a problem, though punctuation is.', 'Choice B', 'Choice C'];
let json = JSON.stringify(suggestions);
// Save to DB
saveToDB(json);
let jsonFromDB = loadFromDB();
let deserializedSuggestions = JSON.parse(jsonFromDB);
console.log(deserializedSuggestions);
we use semicolon (;) for this exact use case in our current project.
So, as per your question, they will be stored in the DB as option1;option2;option3
and when we get it back from the DB we can use the split() method on it to convert it into an array of substrings.
var str = "option1;option2;option3";
var res = str.split(";");
console.log(res);
which would result in (3) ["option1", "option2", "option3"] in the console.
hope this helps.
Related
How can i make the variable 'success' that is passed to 'payment_success.php' below to be somehow encrypted, i don't want the user to know the exact variable name passed. i wanted using post method, but i can't use it for my call back function. Any idea will be a great help
callback: function(response){
const referenced = response.reference;
window.location.href='payment_success.php?success='+referenced;
},
The following is one of tricks I used in a project trying to hide a piece of data.
Assuming your string variable is "123abc".
You may first add a random suffix of three characters , so the string can be:
AC1 C8D E9u Z77 Vux
After that you may use a further trick to put your code "123abc" into a format like the following
1[3 random characters]2[4 random characters]3a[2 random characters]bc[3 random characters]
So the result of 123abc will be like
XXX1XXX2XXXX3aXXbcXXX
so can be any one of the following:
56f134a2rxxq3a43bcccd
97z1zux289873a5tbczwq
Eu11qzv2739u3auubc76x
and so on....
After passing to your PHP script, please extract the correct data.
If you want to be safer, split the characters more further apart by inserting longer random characters in between.
You may use further imagination to do the trick. For example, generate a string which can be random in length of the "mixing codes".
I am using BIRT to design a report based on a database, and one of the fields of the form contain multiple lines, like that :
Site: Place ThePlace
Room: D2 RMD3
InstanceId: OI-RandomChars
The fact is, they are not always in this order, as it is user input (in an other form, not BIRT prompt).
And please note that these fields contain capital letters.
So what I want to do is to extract in three separate columns, so with three regex in JavaScript the Site, the Room, and the InstanceId.
I have tried many things with like catching each row until the end of the line or playing around substrings with various conditions ... and so far I think the best to do is to use string function replace to remove anything different than what I want to catch.
An example for the row Room would be :
row["Log"].replace(/?![Room:\s\S*\s]/, "")
I get an error with this but you can see what I try to do.
Thanks for all the consideration about my problem.
A single regex can become overly complicated and hard to read and mantain for this kind of job.
I would probably consider doing it programmatically like your first instinct was.
First I would consider splitting the string into lines
var lines = string.split("\n\n");
This will split all your double lines into an array
["Site: Place ThePlace", "Room: D2 RMD3", "InstanceId: OI-RandomChars"]
Then cycle trough all your lines and then make your checks.
Your check now can actually be regex if you want, or using substring.
This is an example:
var site, room, InstanceId;
var siteCheckRegex = new Regex("^Site:");
for(var i=0; i<lines.length; i++){
if(siteCheckRegex.test(lines[i])){
site = lines[i].replace("Site:","");
}
[...]
}
It actually depends on what you really want to get out of it and the problem and difference you can find in the user input data.
This question builds off a previous question that I asked:
How do I remove the first character of a string and treat the remaining values as an integer in BigQuery
I am having trouble getting a regular expression that I need for some client work to function. Basically, I want to look through all the cells in a column which has the following types of entries:
customer-o400744190
o400748216
o455239157-new-customer
other similar types with o4552334214 somewhere in the cell
and use something like REGEX_EXTRACT() to parse out or extract "oXXXXXXXXX" from every cell & dump those values into a new column. The data in the column I am pulling from is stored in a string, and can stay that way. Does anyone have any suggestions?
I worked around the problem by just using:
RIGHT(hits_transaction_transactionId, 10)
but know that I am only getting some of the cases that apply. Thus, this is not an acceptable long term solution. Any ideas are greatly appreciated.
Depending on how your data universe is, you could go with /o[0-9]+/
so you would be extracting any ocurrences of o and then at least one number
Is there a way to write to STDOUT without a trailing newline from the Mongo shell? I can't seem to find anything other than print() available.
This is related to my SO question on reading a line from the console. Per #Stennie's comment, it is not possible in the current (2.0.6) version of the Mongo shell.
There might be ways to work around it. You can accumulate the results in an intermediate variable (could be an array, string or any other data structure), then print the entire thing in a single line. Below example illustrates use of an array to capture values from query results, then array is converted to string with comma as a separator. In my case I'm interested in just the _id field:
var cursor = db.getCollection('<collection name>').find(<your query goes here>)
let values = []
cursor.forEach((doc) => values.push(doc._id))
print(values.join(','))
Depending on how many results you're expecting, not sure if space consumed by the intermediate data structure might overwhelm memory. If that's the case can craft the query to return smaller, subsets of data that when added together comprise the full result set you're going for.
This is quite old question, however still relevant, so answering.
One can use printjsononeline().
I need to implement a simple way to handle localization about weekdays' names, and I came up with the following structure:
var weekdaysLegend=new Array(
{'it-it':'Lunedì', 'en-us':'Monday'},
{'it-it':'Martedì', 'en-us':'Tuesday'},
{'it-it':'Mercoledì', 'en-us':'Wednesday'},
{'it-it':'Giovedì', 'en-us':'Thursday'},
{'it-it':'Venerdì', 'en-us':'Friday'},
{'it-it':'Sabato', 'en-us':'Saturday'},
{'it-it':'Domenica', 'en-us':'Sunday'}
);
I know I could implement something like an associative array (given the fact that I know that javascript does not provide associative arrays but objects with similar structure), but i need to iterate through the array using numeric indexes instead of labels.
So, I would like to handle this in a for cycle with particular values (like j-1 or indexes like that).
Is my structure correct? Provided a variable "lang" as one of the value between "it-it" or "en-us", I tried to print weekdaysLegend[j-1][lang] (or weekdaysLegend[j-1].lang, I think I tried everything!) but the results is [object Object]. Obviously I'm missing something..
Any idea?
The structure looks fine. You should be able to access values by:
weekdaysLegend[0]["en-us"]; // returns Monday
Of course this will also work for values in variables such as:
weekdaysLegend[i][lang];
for (var i = 0; i < weekdaysLegend.length; i++) {
alert(weekdaysLegend[i]["en-us"]);
}
This will alert the days of the week.
Sounds like you're doing everything correctly and the structure works for me as well.
Just a small note (I see the answer is already marked) as I am currently designing on a large application where I want to put locals into a javascript array.
Assumption: 1000 words x4 languages generates 'xx-xx' + the word itself...
Thats 1000 rows pr. language + the same 7 chars used for language alone = wasted bandwitdh...
the client/browser will have to PARSE THEM ALL before it can do any lookup in the arrays at all.
here is my approach:
Why not generate the javascript for one language at a time, if the user selects another language, just respond(send) the right javascript to the browser to include?
Either store a separate javascript with large array for each language OR use the language as parametre to the server-side script aka:
If the language file changes a lot or you need to minimize it per user/module, then its quite archivable with this approach as you can just add an extra parametre for "which part/module" to generate or a timestamp so the cache of the javascript file will work until changes occures.
if the dynamic approach is too performance heavy for the webserver, then publish/generate the files everytime there is a change/added a new locale - all you'll need is the "language linker" check in the top of the page, to check which language file to server the browser.
Conclusion
This approach will remove the overhead of a LOT of repeating "language" ID's if the locales list grows large.
You have to access an index from the array, and then a value by specifying a key from the object.
This works just fine for me: http://jsfiddle.net/98Sda/.
var day = 2;
var lang = 'en-us';
var weekdaysLegend = [
{'it-it':'Lunedì', 'en-us':'Monday'},
{'it-it':'Martedì', 'en-us':'Tuesday'},
{'it-it':'Mercoledì', 'en-us':'Wednesday'},
{'it-it':'Giovedì', 'en-us':'Thursday'},
{'it-it':'Venerdì', 'en-us':'Friday'},
{'it-it':'Sabato', 'en-us':'Saturday'},
{'it-it':'Domenica', 'en-us':'Sunday'}
];
alert(weekdaysLegend[day][lang]);