How to convert a Char by the position on the keyboard? - javascript

I need a way to convert the a string, or a char, to it's equivalent on the keyboard on a different language. and as such, in hebrew, for example, "ש" will become "a" or "A".
Couldn't find the proper way to do so without creating a giant switch statement or a dictionary.
any answer on either JS or C# will be great.

Use keyCode of the keydown or keyup events. Property of this event contains code of keyboard key but not code of symbol.
document.addEventListener("keyup", function(event){
console.log(String.fromCharCode(event.keyCode));
});

here is how i do it in javascript
qwerty_mapping = {
"ת":"," ,",":"ת"
,"ף":";" ,";":"ף"
,"ץ":"." ,".":"ץ"
,"ש":"a" ,"a":"ש"
,"נ":"b" ,"b":"נ"
,"ב":"c" ,"c":"ב"
,"ג":"d" ,"d":"ג"
,"ק":"e" ,"e":"ק"
,"כ":"f" ,"f":"כ"
,"ע":"g" ,"g":"ע"
,"י":"h" ,"h":"י"
,"ן":"i" ,"i":"ן"
,"ח":"j" ,"j":"ח"
,"ל":"k" ,"k":"ל"
,"ך":"l" ,"l":"ך"
,"צ":"m" ,"m":"צ"
,"מ":"n" ,"n":"מ"
,"ם":"o" ,"o":"ם"
,"פ":"p" ,"p":"פ"
,"/":"q" ,"q":"/"
,"ר":"r" ,"r":"ר"
,"ד":"s" ,"s":"ד"
,"א":"t" ,"t":"א"
,"ו":"u" ,"u":"ו"
,"ה":"v" ,"v":"ה"
,"'":"w" ,"w":"'"
,"ס":"x" ,"x":"ס"
,"ט":"y" ,"y":"ט"
}
function correctChar(old_char){
if(qwerty_mapping[old_char] == undefined)
{
return(old_char)
}
else
{
return(qwerty_mapping[old_char])
}
}
function correctString(old_string){
new_string = ""
for(i=0;i<old_string.length;i++){
new_string = new_string+correctChar(old_string[i])
}
return new_string;
}

in case someone will look for this answer, It seems like that isn't a clear way of doing that without using a dictionary or a switch statement.
basa.

Related

How to accept all punctuation from form input

I'm creating a language quiz where users can write down their answers, like a translation for example. But I've noticed, when the answer requires punctuation, like a quotation mark, that some devices use a different style of punctuation and that will result in a wrong answer, because the punctuation used in the correct answer is just a bit different.
Here's the javascript I'm using to check answers:
<script>
var answers = {
q1: ["Auto's"]
};
function markAnswers(id) {
$(`#q${id}`).each(function () {
if ($.inArray(this.value, answers[this.id]) === -1) {
$(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
} else {
$(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
}
});
}
$("form").on("submit", function (e) {
e.preventDefault();
const id = e.target.id.replace("formId", "");
markAnswers(id);
$(`#submitId${id}`).each(function () {
this.setAttribute("disabled", true);
this.value = "Check answer";
});
});
</script>
As you can see, here I have an answer that requires a single quote ('), but apparently not all single quotes are equal.
I did find some code to replace specific punctuation and it's this: [^\w\s\']|_
But I'm not sure how to implement it and I would rather just accept the different punctuation. My only concerns are quotation marks and whitespace (as autofill on phones and tablets can create space).
Any suggestion on how to implement this is much appreciated. Thanks!
Edit:
Based on #Don't Panic's earlier versions of his code below (without .clean and .display) I want to make a few tweaks to it, but before I can, the code below always shows ✗ Correct answer = no matter if the answer is typed correctly or not. What could be wrong?
And about the tweaks. I've come to understand that Apple uses Smart Punctuation and this is a feature you can turn off. So I will ask my students to do that. Because I've tested it and without this feature toggled on, it will display a more straight/normal apostrophe and the answer will be accepted as correct. But since apostrophes and perhaps some other punctuation like a comma will be important, I want to add those to the existing line of code ^a-zA-Z\d. And I was thinking to at least ignore periods and extra spaces.
Thank you for all the help!
// Write out your answers without punctuation
var answers = {
q1: ["Autos"]
};
function markAnswers(id) {
$(`#q${id}`).each(function () {
// First, strip out any punctuation the user has entered
let userAnswer = this.value.replace(/[^a-zA-Z\d]/g,'');
// Now check if that "cleaned" value matches your answer
if ($.inArray(userAnswer, answers[this.id]) === -1) {
$(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
} else {
$(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
}
});
}
Take the user's input, strip out all punctuation, do the same to your answer, and compare the two. This way a user can use any punctuation they like, but it will just be stripped out and not part of the comparison.
This won't work if your questions are eg related to grammar, eg if you are testing when and where an apostrophe is correct, of course - in those cases the apostrophe is the answer!
The exact regular expression will depend on what has to be in your questions. Let's say you need all uppper- and lower-case letters and numbers:
$('button').on('click', function() {
markAnswers(1)
});
// Correct answers
var answers = {
"q1": "Auto's"
};
function markAnswers(id) {
$(`#q${id}`).each(function () {
// First, strip out any punctuation the user has entered
let userAnswer = this.value.replace(/[^a-zA-Z\d]/g,'');
// Strip any punctuation from the right answer
let correct = answers[this.id].replace(/[^a-zA-Z\d]/g,'');
// Now check if they match
if (userAnswer !== correct) {
$(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
} else {
$(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
What is the plural of <b>Auto</b>?
<input id='q1' type='text'>
<button>Check!</button>
</div>
To answer your new question - your code works fine for me.
I've added a button handler to actually run the check, but otherwise this is a copy-paste of your code.
If I type asdf, I get "✗ Correct answer = Autos", which is correct;
If I type autos, I get "✗ Correct answer = Autos", which is correct (lower case "a" instead of "A");
If I type Autos, I get "✓ Correct!", which is correct;
If I type "Auto's" (including those quotes), I get "✓ Correct!", which is correct;
$('button').on('click', function() {
markAnswers(1)
});
// Write out your answers without punctuation
var answers = {
q1: ["Autos"]
};
function markAnswers(id) {
$(`#q${id}`).each(function () {
// First, strip out any punctuation the user has entered
let userAnswer = this.value.replace(/[^a-zA-Z\d]/g,'');
// Now check if that "cleaned" value matches your answer
if ($.inArray(userAnswer, answers[this.id]) === -1) {
$(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
} else {
$(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
What is the plural of <b>Auto</b>?
<input id='q1' type='text'>
<button>Check!</button>
</div>

use of Regular expression

While using Javascript, I'm making a limit for the product number in front-end.
The product number should be xxxxx 5 digits number or xxx-xxx style 6 numbers.
What I planned was replacing non-correct text characters to "" for each keypress
and called in front like this onkeypress = "checkonlynumdash();"
for the function, my code is like below.
function checkonlynumdash() {
e = window.event;
var keypress = String.fromCharCode(e.keycode);
var numdashkey = "";
numdashkey = /^[-]|[^0-9-]/;
return numkey.test(keypress);
}
while using window.event, I tried to control the real time keypress, but it
does not seem working with replace. Hope someone can point out missing part.
I see two issues:
e.keycode
I would change to
e.charCode
and use another regex: /[\d-]/, it is more simple.
So the result might be:
function checkonlynumdash() {
e = window.event;
var keypress = String.fromCharCode(e.charCode);
var numdashkey = /[\d-]/;
return numdashkey.test(keypress);
}
Also I can't understand your original regexp: /^[-]|[^0-9-]/ symbol ^ means 'in the beginning of the string' or 'not'.
You can try Simple Mask, it is jQuery plug-in to make masks on input fields.
Usage:
$('input').simpleMask({
'mask': ['####-####','#####-####']
});
Demo

How to remap keyboard within the same textarea

Currently i am doing a project with remapping characters to words by detecting the keyup function. Unfortunately, i have only been able to retrieve the first character and remap to the word i want. In my project, i need to directly retrieve all of my keyboard input and directly convert it to the word that i want within the same textarea. For example when i type in the textarea, it will convert to "are" directly. I don't know why it stopped retrieving the second character and remapping not function. Below is my code, hope someone can tell me my error. Thank you.
<textarea class="width-100" id="translated-text" onkeyup="myFunctionkey(event);" rows="10"></textarea>
<script>
function myFunctionkey(e) {
conversion();
}
function conversion(){
var x = document.getElementById('translated-text');
if(x.value == 'a'){
x.value='yes';
}
if(x.value == 'q'){
x.value = 'are';
}
}
</script>
From what I understand, you only want to grab the input and replace a key stroke with a complete word.
Maybe this will do. I've changed onkeyup to onkeypress because this is more reliable from what I remember.
<textarea id="translated-text" cols="50" rows="10" onkeypress="replaceInputChar(event);"></textarea>
<script type="text/javascript">
//create replacement map
var map = {
"a": "and",
"b": "bold",
"c": "change"
};
function replaceInputChar(e)
{
var ctl = document.getElementById("translated-text"); //control
var char = String.fromCharCode(e.keyCode); //typed char
if (char in map) //check if letter is defined in map
{
//insert replacement instead of letter
if("selectionStart" in ctl)
{
//in modern browsers we can easily mimic default behavior at cursor position
var pos = ctl.selectionStart;
ctl.value = ctl.value.substr(0, pos) + map[char] + ctl.value.substr(ctl.selectionEnd);
ctl.selectionStart = pos + map[char].length;
ctl.selectionEnd = ctl.selectionStart;
}
else
ctl.value += map[char];
if ("preventDefault" in e) //modern browser event cancelling
e.preventDefault();
else
{
//old browser event cancelling
e.returnValue = false; //IE8
return false;
}
}
}
</script>
You should use comparison operator '==' instead of assignment operator '=' while remapping the value, like this:
x.value=='a'
Edit:
You should check the updated code for your problem here:
https://jsfiddle.net/o4coLr5t/1/
Now, the characters you choose to remap in javascript will display the string, that you map the character to. Otherwise it will display nothing on pressing keys. So, try and add all the character keycodes to the javascript code. Hope that helps.

is it possible to check the XMLHttpRequestObject.responseText value using if condition

Is it possible to check the XMLHttpRequestObject.responseText value using if condition instead of just displaying it?
I have tried like this.
var a=XMLHttpRequestObject.responseText;
if(a=="false")
{
document.getElementById("show_mark").innerHTML =a;
}
I know its wrong,but i need to do like this.Is there any other alternative way for doing this?Help me i am completely a newbie to AJAX.
It is possible that the response text has added white spaces. To remove white spaces at the start and end of a string use string.trim().
In your case a=a.trim()
If trim is not available in your browser's JavaScript interpreter add in
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
Source
Finally i found the mistake.Its not the white spaces around the value.Actually its all the html tags like <html><body>false</body> etc., I removed these characters with the help of this code. I got the answer.
var a=XMLHttpRequestObject.responseText;
a = a.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";
});
var b = (a.replace(/<\/?[^>]+(>|$)/g, "")).trim();
if(b=="false")
{
document.getElementById("show_mark").innerHTML =b;
}
Thanks for the support.

Translate user selected text with Google Translate API (and jQuery)

I am working on some JavaScript for a website with content in multiple languages. I would like to use the Google Translate API to allow the user to select a word (or phrase) and have a translation automatically provided. For the time being, I'm simply having it alert the result for testing.
This is what I have so far:
google.load("language", "1");
function getSelection() {
var selection = (!!document.getSelection) ? document.getSelection() :
(!!window.getSelection) ? window.getSelection() :
document.selection.createRange().text;
if (selection.text)
selection = selection.text
console.log(selection);
return selection
}
$(document).ready(function() {
$(window).mouseup(function() {
var selection = getSelection();
if (selection != "") {
google.language.translate(selection, "", "en", function(result) {
if (!result.error) {
alert(result.translation);
} else {
alert(result.error);
}
});
}
});
});
The problem that I'm running into is that my getSelection() function is returning a Range objects, which is apparently incompatible with google's language.translate() function. All I really need is a way to retrieve the actual text from the Range as a string so I can pass that. As far as I know there's some really easy, obvious way to do this that I'm just missing (yes, I tried using selection.text), but my experience with JavaScript is limited and Googling it hasn't revealed anything useful.
Can anyone help?
Try jQuery google translate - http://code.google.com/p/jquery-translate/.
Unsurprisingly there was a really obvious answer that I just completely missed. selection.toString()...
You can do something like this:
function getSelection() {
var selection = window.getSelection ? window.getSelection() + ''
: document.selection.createRange().text;
return selection
}
By concatenating an empty string to the result of the getSelection() method, its value gets converted to string, it's a common short-hand, equivalent to call the toString method, because:
var test = {
toString: function () {
return 'foo';
}
};
test+'' == 'foo'; // true
You also don't need to use the double logical negation (!!) in a ternary, because the first operand, the condition, its automatically converted to Boolean.

Categories

Resources