Declare variable in js - javascript

I have a problem using quotation marks in js...
I have an input field using this js-function
function validate(xyz) {
"+umum+" == "yeah_it_is_ok";
if(xyz == ""+umum+"") {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
What do I have to insert in the input-field to get the Hoera message?$
In other words, what is the function of a " or a + in js?

You don't have a syntax error in the function declaration,
but it will fail at execution time, because umum is not defined;
and surely you have a semantic error, because the only way to get "Hoera"
is to declare the umum var first and call the validate function later:
var umum;
validate("test value");
Of course, it always give a "too bad!" message unless you pass ""+undefined+""
as parameter. I think the right function should be:
function validate(xyz) {
var umum = "yeah_it_is_ok"; // or whatever you want to validate with..
if(xyz == umum) {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
In this case, when calling validate("yeah_it_is_ok") you'll get an "Hoera!".

You would want to declare a variable like this:
var umum = "yeah_it_is_ok";
Note the var keyword and the use of a single equals for assignment.
Also, a pair of " characters is used to enclose a string variable, and the + will concatenate two strings. However, if you wish to have a double-quotation within a string you need to escape it with a backspace \. For example:
if(xyz == "\"+umum+\"") {

Single- and double-quote characters are used to delimit string constants. The + character is an operator that serves several purposes, including string concatenation, numeric addition, and asserting numeric "positiveness" (used often for its implicit side effects).

I think you mean to write your function like this.
function validate(xyz) {
umum = "yeah_it_is_ok";
if(xyz == umum) {
alert("Hoera!");
return true;
} else {
alert("Too bad!");
return false;
}
}
So then to answer your question, you can put the string that your looking for into the input-field. Which, since you don't have an input field in your example, we can just call the function with the correct string.
validate("yeah_it_is_ok");
Also it seems like you were thinking that you can use " or + in a variable. You can't do that. As others have suggested, you should learn the basics of JavaScript. w3schools.com and the Mozilla Developer Network are good places to do that.
http://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en-US/learn/javascript

I believe you put a \ infront of it
so like
if(xyz == "\"+umum+\"") {

Related

convert string to boolean and compare with if condition in js

I have an attribute where I have got condition .I took that condition from tag's attribute now I want place that condition in if block and get result.
my code:-
<div myCondition="1 == 2" id="hey"></a>
<script>
var a = document.getElementById('hey');
var x = a.getAttribute('myCondition');
if(x){
console.log('accepted')
}else{
console.log('not accepted')
}
</script>
above program should return not accepted
value of myCondition attribute can be very complex for example:-
'hello' == 'hello'
5>1 etc
I guess what you need is the eval function. As it says in the provided link:
The eval() function evaluates JavaScript code represented as a string.
So, you can change your code like this:
if( eval(x) ){
console.log('accepted')
}else{
console.log('not accepted')
}
P.S: That being said, I don't think doing it like this really safe.

javascript format issues with ()

i got a little code but it doesnt work. i think i have an error with the ( ) cause there are too many x)
code:
if (structure == null) {
console.log('so far so good: ');
if (_.sum(Game.getObjectById(57 f5db55fc5a39220c785df5).store) < Game.getObjectById(57 f5db55fc5a39220c785df5).storeCapacity) {
if (creep.transfer(Game.getObjectById(57 f5db55fc5a39220c785df5), RESOURCE_ENERGY, creep.energy) == ERR_NOT_IN_RANGE) {
// move towards it
creep.moveTo(Game.getObjectById(57 f5db55fc5a39220c785df5));
}
}
}
anyone can understand what went wrong here? :p
You need to quote your IDs (example: 57f5db55fc5a39220c785df5 -> '57f5db55fc5a39220c785df5').
Since you're not enclosing them with quotes, it's regarded as an non-existent variable by the interpreter. And if you got some illegal characters there, it will fail even before trying to resolve the variable.
57f5db55fc5a39220c785df5 can't be a variable name, nor can it be an integer as it contains characters - so it's a string. In javascript, you need to enclose strings with " or '
if (structure == null) {
console.log('so far so good: ');
if (_.sum(Game.getObjectById("57f5db55fc5a39220c785df5").store) < Game.getObjectById("57f5db55fc5a39220c785df5").storeCapacity){
if (creep.transfer(Game.getObjectById("57f5db55fc5a39220c785df5"), RESOURCE_ENERGY, creep.energy) == ERR_NOT_IN_RANGE) {
// move towards it
creep.moveTo(Game.getObjectById("57f5db55fc5a39220c785df5"));
}
}
}

JavaScript - Regex to remove code / special characters / numbers etc

Answer #Wiktor Stribiżew suggested:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? true : false;
}
Hello during the creation of an array I have a function that will not allow words with certain characters etc to be added to the array
function myValidate(word) {
// No one letter words
if (word.length === 1) {
return true;
}
if (word.indexOf('^') > -1 || word.indexOf('$') > -1) {
return true;
}
return false;
}
It seems like not the proper way of going about this and ive been looking into a regex that would handle it but have not been successful implementing it, tried numerous efforts like:
if (word.match('/[^A-Za-z]+/g') ) {
return true;
}
can some one shed some light on the proper way of handling this?
I suggest using a simpler solution:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? false : true;
}
var words = ["Fat", "Gnat", "x3-2741996", "1996", "user[50]", "definitions(edit)", "synopsis)"];
document.body.innerHTML = JSON.stringify(words.filter(x => myValidate(x)));
Where:
word.length === 1 checks for the string length
/[^A-Z]/i.test(word) checks if there is a non-ASCII-letter symbol in the string
If any of the above condition is met, the word is taken out of the array. The rest remains.
EDIT: using test instead of match
You want to use test() because it returns a bool telling you if you match the regex or not. The match(), instead, always returns the matched elements. Those may be cast to true by coercion. This is not what you want.
To sum it all up you can just use this one-liner (no if needed and no quotes either, cannot get any simpler):
return word.test(/^[a-zA-Z][a-zA-Z]+$/); // two letter words
You should whitelist characters instead of blacklisting. That's one of the principles in security. In your case, don't tell what is wrong, but tell what is right:
if (word.test('/^[a-zA-Z]+$/')) { // two letter words
return false;
}
This will return false for all words that contain ONLY [a-zA-Z] characters. I guess this is what you want.
Your regex, instead, looked for illegal characters by negating the character group with the leading ^.
Two recommendations:
Just use regex in a positive way (without negation) and it'll be a lot easier to understand.
Also, validation functions normally return true for good data and false for bad data.
It is more readable this way:
if (validate(data))
{
// that's some good data we have here!
}

Javascript: Ensure Input is Numbers Only

I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.

Javascript Replace - Regular Expression

I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. Something like
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this.
onkeyup="testRegex(this.value)";
It is not .replace() it is .test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}

Categories

Resources