Check for multiple hash substrings - javascript

I'm trying to check for two different hash substrings and execute different code depending. This is what I have right now:
Javascript
if(window.location.hash.substring(confirm) {
$('.confirm').click();
}
elseif(window.location.hash.substring(thanks) {
$('.thanks').click();
}
Any idea what I am doing wrong?

Use indexOf with quotes to denote the string you want to search:
if(window.location.hash.indexOf('confirm') >= 0) {
$('.confirm').click();
}
else if(window.location.hash.indexOf('thanks') >= 0) {
$('.thanks').click();
}
BTW, in your original implementation, you were also missing ) in the if condition.

Related

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!
}

JS str replace Unicode aware

I am sure there is probably a dupe of this here somewhere, but if so I cannot seem to find it, nor can I glue the pieces together correctly from what I could find to get what I need. I am using JavaScript and need the following:
1) Replace the first character of a string with it's Unicode aware capitalization UNLESS the next (second) character is a - OR ` or ' (minus/dash, caret, or single-quote).
I have come close with what I could find except for getting the caret and single quote included (assuming they need to be escaped somehow) and what I believe to be a scope issue with the following because first returns undefined. I am also not positive which JS/String functions are Unicode aware:
autoCorrect = (str) => {
return str.replace(/^./, function(first) {
// if next char is not - OR ` OR ' <- not sure how to handle caret and quote
if(str.charAt(1) != '-' ) {
return first.toUpperCase(); // first is undefined here - scope??
}
});
}
Any help is appreciated!
Internally, JavaScript uses UCS-2, not UTF-8.
Handling Unicode in JavaScript isn't particularly beautiful, but possible. It becomes particularly ugly with surrogate pairs such as "🐱", but the for..of loop can handle that. Do never try to use indices on Unicode strings, as you might get only one half of a surrogate pair (which breaks Unicode).
This should handle Unicode well and do what you want:
function autoCorrect(string) {
let i = 0, firstSymbol;
const blacklist = ["-", "`", "'"];
for (const symbol of string) {
if (i === 0) {
firstSymbol = symbol;
}
else if (i === 1 && blacklist.some(char => char === symbol)) {
return string;
}
else {
const rest = string.substring(firstSymbol.length);
return firstSymbol.toUpperCase() + rest;
}
++i;
}
return string.toUpperCase();
}
Tests
console.assert(autoCorrect("δα") === "Δα");
console.assert(autoCorrect("🐱") === "🐱");
console.assert(autoCorrect("d") === "D");
console.assert(autoCorrect("t-minus-one") === "t-minus-one");
console.assert(autoCorrect("t`minus`one") === "t`minus`one");
console.assert(autoCorrect("t'minus'one") === "t'minus'one");
console.assert(autoCorrect("t^minus^one") === "T^minus^one");
console.assert(autoCorrect("t_minus_one") === "T_minus_one");

Jquery Validate Multiple Conditions

I'm trying to validate a field with multiple conditions. I've got validation working with a single condition, but I'm not sure how to go about adding in addl conditions. Here's what I have so far:
priceEstimate: {
required: function() {
return $('#jobType').val() != '8';
}
}
I also need to make sure that the value of #jobType does not equal '9' or '10' either. I tried using an or operator, and that didn't seem to do the trick.
Any help would be greatly appreciated.
priceEstimate: {
required: function() {
var jobType = $('#jobType').val();
if (jobType < '8' && jobType > 10)
{
return true;
}else{
return false;
}
}
}
There are likely simpler ways to write it... but that will do ya. http://www.w3schools.com/js/js_comparisons.asp
In response to Jeremy's comment:
priceEstimate: {
required: function ()
{
var jobType = Number($('#jobType').val());
var _return = true;
switch (true)
{
case (jobType <= 1):
case (jobType >= 8 && jobType <= 10):
  _return = false;  
break;
}
return _return;
}
}
Ok, what we did here is a cascading switch. The expression is set to true, so it will run each case... we're then putting our logic in each individual case.
We know we don't want 1 or 0, so I have just have it set to false if it is equal to 1 or below, without a break in that case, it will simply run on to the next case and validate even further, so you'll want to try and keep the cases in order least -> greatest if nothing for the sake of your own sanity, lol.
Also I'm using Number() to flesh out the numeric value in the input, just in case, this way we also don't have to encapsulate all of our checks with quotes ('10') and they're treated like actual numbers and not just representations that may be translated into something that would fail the logic your striving for.

Declare variable in js

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+\"") {

Categories

Resources