I'd like to use the JavaScript toLocaleUpperCase() method to make sure that the capitalization works correctly for the Turkish language. I cannot be sure, however, that Turkish will be set as the user's locale.
Is there a way in modern browsers to set the locale in run time, if I know for sure that the string is in Turkish?
(I ran into this problem while thinking about Turkish, but actually it can be any other language.)
There isn't really anything much out there but I came across this JavaScript setlocale function script that you might find useful.
You unfortunately cannot set locale during runtime. All hope is not lost though, there are many good libraries on npm for you to use. Check out https://www.npmjs.com/package/upper-case and https://www.npmjs.com/package/lower-case for example, it will work for many other languages too.
If that's too much, you can roll your own simple library:
var ALL_LETTERS_LOWERCASE = 'abcçdefgğhıijklmnoöprsştuüvyz';
var ALL_LETTERS_UPPERCASE = 'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ';
function toLowerCaseLetter(letter) {
letter_index = ALL_LETTERS_UPPERCASE.indexOf(letter);
return ALL_LETTERS_LOWERCASE[letter_index];
}
function toLowerCase(my_str) {
var lower_cased = ''
for (letter of my_str) {
lower_cased += toLowerCaseLetter(letter);
}
return lower_cased;
}
console.log(toLowerCase('ÇDEFGĞHIİJKLMNOÖPRSŞTUÜ'))
Very similar for upper case version.
This option may not have existed back in 2013 but may help new visitors on this topic:
According to MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase) the function toLocaleUpperCase takes an optional parameter 'locale'.
Setting the right language tag is a topic on its own (https://www.w3.org/International/articles/language-tags/). Simplest example looks like this
'selam dünya'.toLocaleUpperCase('tr'); // SELAM DÜNYA
Related
I have an idea for a game where people can type in some simple instructions for their character like player.goLeft() or player.attackInFront() and for that I have people type their code into a text box and then I parse it into eval(). This works well but it also allows people to change their own character object by typing things like player.health = Infinity; or something similar. I have a list of functions I want to allow people to use, but I am unsure how to restrict it to only use them.
I understand that the whole point of not letting people use eval is to avoid accidental cross-site scripting but I am unsure on how else to do this. If you have a suggestion please leave a comment about that.
I asked some people around on what to do and most suggested somehow changing scope(which is something I was not able to figure out) or to add some odd parameter to each function in my code that would be required to be a specific string to execute any function, but that seems hacky and since I am making the game in browser with p5js it would be easy to just inspect element and see what the password is.
basically every character has variable called "instruction" which is just a string of javascript. Then every frame of the game I execute it by doing eval(playerList[i].instruction);
tl;dr, how can I only allow specific function to be executed and not allow any others?
EDIT: I forgot to mention that I also am planning to provide player with information so that people can made code that would adapt to the situation. For example there will be parameter called vision that has vision.front and vision.left etc. These variables would just say if there is an enemy, wall, flower, etc around them in a grid. Some people suggested that I just replace some functions with key words but then it compromises the idea of using if statements and making it act differently.
EDIT 2: Sorry for lack of code in this post, but because of the way I am making it, half of the logic is written on server side and half of it works on client side. It will be a little large and to be completely honest I am not sure how readable my code is, still so far I am getting great help and I am very thankful for it. Thank you to everybody who is answering
Do NOT use eval() to execute arbitrary user input as code! There's no way to allow your code to run a function but prevent eval() from doing the same.
Instead, what you should do is make a map of commands the player can use, mapping them to functions. That way, you run the function based on the map lookup, but if it's not in the map, it can't be run. You can even allow arguments by splitting the string at spaces and spreading the array over the function parameters. Something like this:
const instructions = {
goLeft: player.goLeft.bind(player),
goRight: player.goRight.bind(player),
attackInFront: player.attackInFront.bind(player)
};
function processInstruction(instruction_string) {
const pieces = instruction_string.split(' ');
const command = pieces[0];
const args = pieces.slice(1);
if (instructions[command]) {
instructions[command](...args);
} else {
// Notify the user their command is not recognized.
}
};
With that, the player can enter things like goLeft 5 6 and it will call player.goLeft(5,6), but if they try to enter otherFunction 20 40 it will just say it's unrecognized, since otherFunction isn't in the map.
This issue sounds similar to the SQL Injection problem. I suggest you use a similar solution. Create an abstraction layer between the users input and your execution, similar to using parameters with stored procedures.
Let the users type keywords such as 'ATTACK FRONT', then pass that input to a function which parses the string, looks for keywords, then passes back 'player.attackInFront()' to be evaluated.
With this approach you simplify the syntax for the users, and limit the possible actions to those you allow.
I hope this isn't too vague. Good luck!
From your edit, it sounds like you're looking for an object-oriented approach to players. I'm not sure of your existing implementation needs, but it would look like this.
function Player() {
this.vision = {
left: '',
// and so on
}
}
Player.prototype.updateVisibilities = function() {
// to modify the values of this.visibility for each player
}
Player.prototype.moveLeft = function() {
}
Don't give the user an arbitrary interface (such as an input textfield that uses eval) to modify their attributes. Make a UI layer to control this logic. Things like buttons, inputs which explicitly run functions/methods that operate on the player. It shouldn't be up to the player as to what attributes they should have.
When creating an if block, I was wondering if there was any reason beyond personal preference to use the standard bracket formatting vs the second one I listed.
I've run code in the second format without any obvious issues (no ASI or unexpected errors), just looking for some clarification or insight on if there could be any possible issues in the future if I permanently switch to this style.
// Standard formatting
if (true) {
} else {
}
// Other formatting
if (true) {
}
else {
}
Spaces and tabs are not considered to be significant in Javascript in most cases. (I believe all, but I can't find a source for that)
You can technically put all of your code on one line (as most minification algorithms do), but that won't be very readable. In your own code, it comes down to solely personal preference, it will not cause any errors or cause the code to run slower if there are spaces (though more spaces will take longer to load if the JS is not minified).
Best practice is to keep your code style consistent throughout your projects.
None, they are equivalent if you wanted you could put the code in one line as well and it would work. Usually people have personal preferences, as well as some companies require you to write the code in a specific way in order to standardize it and make it so anyone taking over your project knows what to expect.
You don't even need the brackets, it wil just work:
http://jsfiddle.net/4ywahnof/1/
(function () {
var t = 1;
if (t == 1) alert("hi");
else alert("no hi");
})();
I've been writing C/C++/C# for decades, and have used JavaScript as needed for web projects, but want to expand that and do some more in-depth development with Canvas and JavaScript.
My concern is how easily you can make mistakes like setinterval() instead of setInterval(), for example. I'm using VisualStudio and have Telerik's JustCode plugin that does some static analysis, but there's so much that it doesn't check.
I also worry about calling object methods or properties that just don't exist. I understand why these things empower the language and developer with greater flexibility, but how do I best protect myself from the unintended consequences of that flexibility?
I struggled with JavaScript's dynamically-typed nature for a long time too. It turned out to be quite liberating when I finally made peace with it. Here's the mantra that has worked for me:
Program correctness is the most important thing. If I am confident my program exhibits the correct behavior, either my types are correct, or any existing typing errors don't effect program behavior.
This shift in thinking puts more of an emphasis on testing -- which is a good thing. If your tests are well-written, and comprehensive, then type errors will be caught.
I also tend to employ much more of a functional paradigm in my JavaScript coding: if you are not mutating state, strong typing has less meaning.
Of course if you really feel that strong typing is important, there is always TypeScript, which compiles directly to JavaScript and is, by all accounts, an excellent language.
Good design is the answer. Just because it's Javascript and it gives you a lot of freedom doesn't mean the principles you've used until now are any less valid. Design by interfaces (or even better, by contract), make class diagrams, put pen to paper, etc. Do be careful about Javascript's very own brand of object-orientedness, learn about it and the associated patterns (SO has many questions about them) and await ES6 Harmony eagerly.
If you want an IDE, or at least an environment, that tells you what's wrong in a readable and easy-to-use fashion, I recommend simply using your favorite browser's console (your fav browser should be FF or Chrome). Firefox + Firebug is particularly good though, and a favorite among many Web developers. The console, just like in Python, allows you to test snippets of code and to solve your naming errors very fast.
When I finished university I was a promising young lad and was sure that I will have no problems with finding some work. After a while... Bang! The World Economic Crisis struck. So I had to accept some cheap and ugly job and after I fed up with them, I started to search for something better and I risked everything. You might wonder why I am telling all this to you in a semi-scientific site. I am telling you, because through my story you will understand why I am answering the way I am answering. After 3 years of searching for my place and constantly training and educating myself I've got an offer from a small group of programmers, who were using some technologies which were very alien to me. I have joined them and I had to learn many things: .NET framework, Visual Basic, Javascript, jQuery, CSS, Telerik, a lot of libraries. I knew this was my chance to stabilize my position and I was a very trained learner (I have been constantly learning, but in different areas), so I have spent two weeks working 16 hours instead of 8 and at the end I was a constructive member of the team, still a bit rusty in the newly learned languages and technologies, but my results were quite decent. Shortly after that I became used to all the things used there and had no problems.
The thing is that I learned Javascript while learning a lot of other things as well and working in the meantime, having a tight schedule for the tasks. Just like you, I did not like Javascript has no types. I do not like it even now, after all those years. But I had no time to make it more comfortable to me and now I am so used to it that I am too lazy to create something which would help me and the thing would no longer help me.
If you do not want to get used to it the hard way, I believe something like this would help you:
function StrongType(weakValue) {
//int
this.i = function() {
return parseInt(weakValue);
};
//float
this.f = function() {
return parseFloat(weakValue);
};
//string
this.s = function() {
return weakValue + "";
};
//boolean
this.b = function() {
return !!weakValue;
};
//change
this.c = function(newValue) {
weakValue = newValue;
};
//natural
this.n = function() {
return weakValue;
};
}
This would help you to make sure you always know the type you are using. Function names:
You could create a strategy for yourself about how a name is typed and use that for all your functions and variables. If you are using some function and its name is not ok for you, then you can do something like this:
function MyNameHelpers() {
this.setTimeOut = function(callback, interval) {
return setTimeout(callback, interval);
};
}
Also, let's suppose you have a foo object and you want to use its bar member, possibly with parameters:
function MemberUser() {
this.useMember = function(owner, member, error, errorParams) {
if (!!owner) {
return owner[member];
} else {
//error is a function to handle the case when owner is falsy
return error(errorParams);
}
};
this.callMethod = function(owner, member, params, error, errorParams) {
if (!!owner) {
return owner[member](params);
} else {
//error is a function to handle the case when owner is falsy
return error(errorParams);
}
};
}
The codes above are just illustrations, I did not test/use them, maybe things are needed to be added and so on, but you get the idea. You will either get used to Javascript like I did, or create a library to prevent you from making mistakes. It is your choice.
Apparently the task I asked about earlier (JavaScript Automated Clicking) is impossible in JavaScript, or at the very least extremely difficult.
However, I have found the documentation on Selenium and how to use it extremely uninviting and difficult to understand.
Perhaps someone could help me translate this code to Selenium or, alternatively, help me with particular elements I'm having difficulty with.
function pausecomp(ms) {
ms = ms + new Date().getTime();
while (new Date() < ms){}
}
var itemlist, totalnumber, i;
itemlist = document.getElementsByClassName("image");
totalnumber = parseInt(document.getElementById("quickNavImage").childNodes[3].firstChild.firstChild.nodeValue.replace(/[0-9]* of /, ""));
for(i = 0; i < totalnumber; i = i + 1) {
console.log(i);
itemlist[i].childNodes[1].click();
pausecomp(3000);
}
Now, I know I can get elements by Class Name in Selenium, but how do I get specific child nodes?
Likewise, how do I use regex to cut out the total number of items that needs to be clicked? It is only available in text form.
And finally, how do I iterate in Selenium?
Please note, I have no available programming environments on these computers. So I cannot use Python, C#, etc. hooks unless they can be directly imported into the Selenium IDE itself. However, the documentation is difficult for me to understand, so I don't believe that is possible.
I figured it out. Please take a look at my previous linked post. I was being an idiot. I'll put the answer up there.
Say I have a variable
tab_something
I need to drop the tab_ bit.
In php it's easy, using str_replace...
Will
tabSelect = document.location.hash.substr(1,document.location.hash.length);
(which would always be tab_something)
document.write(tabSelect.replace(/tab_/i, ""));
Work the way I would like it to, consistently across all modern browsers (ie6+) ?
Cheers.
Abusing source code rewrite as a substitute for reflection is … possible. I hate to state the obvious, but: maybe take a step back and see if you can reshape the project a bit, such that you can come up with a cleaner solution?
A couple of things:
document.location will be deprecated at some point by document.URL, consider using window.location.
Consider also using String.substring, since it is part of the ECMA-262 Spec.
var tabSelect = window.location.hash.substring(1); // remove "#"
tabSelect = tabSelect.replace(/tab_/i, ""); // remove "tab_"
It will work on old and modern browsers.
If document.location.hash always contains tab_ + some other string that you wish to retrieve, why not take advantage of the prefix always being the same length? You already have call substring() so why not let this function cut of a few more chars?
window.location.hash.substring(5)
Thanks to CMS for pointing out that window.location is preferred to document.location.
Yes it will. And also note that you don't have to use regular expressions in .replace(), .replace('tab_', ''); will do just fine.
Yes that is a standard JavaScript function that's been around long enough to cover all modern browsers ie6 and above. Should work just fine.
You could also use substring if you know it will always be the first 4 characters. tabSelect.substring(4) will give you everything starting the first character after tab_ (it is 0-based).