JavaScript /regex/.test() give a function as parameter [duplicate] - javascript

This question already has an answer here:
Strange JavaScript idiom - what does "/xyz/.test(function(){xyz;})" do?
(1 answer)
Closed 9 years ago.
I check the Mollzia and MS document, I only find regex.test(str) API. However, I saw a usage of test(function(){}) in John Resig's Class.js which made me very confused.
source code: class.js
the code:
fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
and
fnTest.test(prop[name])
what they do?
on firebug
console.log(/xyz/.test(function(){xyz;}))//true;
console.log(/xyz/.test(function(){}))//false;
console.log(/xyz/.test(function(){console(xyz);}))//true; console(xyz) not run

I think that
fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
is a form of browser feature detection. He's passing a function object to the "test" method, which should convert the function object to a string. If the result of that actually does include the string "xyz", then the "fnTest" variable is initialized to the regex /\b_super\b/. If not, which would be the case when a JavaScript environment wouldn't stringify a function like that for some reason (hint: IE), then "fnTest" is initialized to a regex that'll match anything.

Related

Please interpret this java script line of code [duplicate]

This question already has answers here:
What is "?:" notation in JavaScript?
(5 answers)
Closed 6 years ago.
Can someone interpret this javascript line for me?
mouseWheelEventName = $.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel',
Need to know what "?" does, and what 'DOMMouseScroll' : 'mousewheel', is saying particularly the "," at the end of the line... why isn't it a ";"
Thank you.
This is a ternary operator, used as a shorthand conditional statement:
it's the same as saying:
if ($.browser.mozilla) {
mouseWheelEventName = 'DOMMouseScroll';
} else {
mouseWheelEventName = 'mousewheel';
}
The first piece before the = is declaring a variable (mouseWheelEventName) dependent on the following condition.
The next piece between = the ? is the condition (is $.browser.mozilla true?).
Immediately after the ? is the then portion (if the condition is true, set the variable mouseWheelEventName to the string DOMMouseScroll).
After the : is the else (if the condition is NOT true, set the variable mouseWheelEventName to the string mousewheel).
Further reading:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
As for why there is a comma at the end of it, we'd need to see a more complete code sample including what follows that to say for certain. If I had to guess, I would say the author of the code was chaining variable statements. This answer may shed some light for you: Javascript best practices, why to use comma to chain function/variable declarations? (see chosen answer)

Use of $ in regular method [duplicate]

This question already has answers here:
Why would a JavaScript variable start with a dollar sign? [duplicate]
(16 answers)
Closed 8 years ago.
I go over some code and I saw the following code
var failedExtPlugins = PluginR.$getFailPlug();
It seems that this time the $ is not refer to jquery object (yes I know that when you use Jquery you start with $) I guess,so what does it mean?
it look like regular method...but way the use $
It looks just like a part of a name. I like to use $ in a name of jQuery objects I have. Maybe author has some thoughts about that.
Its a jQuery wrapped object. $ObjectName reflects that its holding a reference of jQuery wrapped object of particular dom object.
For Example:
var $obj = $("#SomeId");

Javascript How do I force a string + variable to be evaluated as a variable [duplicate]

This question already has answers here:
is there a way to execute a function when I have its name in a string [duplicate]
(2 answers)
Closed 9 years ago.
Im not even sure how to word this and is probably why I am having trouble finding an answer in google.
When the code is run currentCardRow will equal 1 therefore it should be cardSelected1 which is what is shown in the console.log. I need it to go a step further because cardSelected1 is a variable and I need it to evaluate show in the console log as Invitation. Invitation is an example of a variable for cardSelected1.
I am not sure on what the correct syntax is to make this happen.
var currentCardSelected = "cardSelected" + currentCardRow;
Thanks for your help!
JavaScript has an Eval() function which allows you to evaluate strings as javascript code.
For example
var bar = "123";
var foo = "bar";
console.log(eval(foo));
will print "123" to the console.
For more information on eval, you can consult the MDN docs.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Generally, the use of eval() is considered poor practice as it makes the code difficult to read. There are likely more elegant solutions to implement what you have described, however, eval will solve your current problem.
var currentCardSelected = eval("cardSelected" + currentCardRow);
This is how my problem is fixed.

isJSON in javascript, without try/catch [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to check if a string is a valid JSON string in JavaScript without using Try/Catch
The question was already asked here : How to check if a string is a valid JSON string in JavaScript without using Try/Catch. No valid answer was given, even the validated one wasn't answering the question.
So it seems the only way to not doing this using try/catches is via regexps; the regexp given in one of the answers was only validating against eval, so a simple string like "2001-05-06" would pass the regexp, even though it's not JSON.
So has anyone a good regexp to validate against a well formed JSON string ?
Using a regex instead of a try/catch is replacing a correct solution with a non working hack.
The link you give suggests to change the JSON parsing code that you can modify to not throw an exception. I would suggest replacing in json_parse.js the following code
error = function (m) {
// Call error when something is wrong.
throw {
name: 'SyntaxError',
message: m,
at: at,
text: text
};
},
by the call of a callback you would provide.
But to be frank, my most reasonable suggestion would be to use try/catch. That's the best tool you have here. Note that my JSON.parse modification "suggestion" supposes to manage the break from all loops/recursions, which is precisely what an exceptions does.
from link try this
var jsonData = '{"1":"test"}';
if (/^[\],:{}\s]*$/.test(jsonData.replace(/\\["\\\/bfnrtu]/g, '#'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
alert('ok');
}else{
alert('no');
}

Can you set an undefined variable as a function parameter? [duplicate]

This question already has answers here:
Undefined variable as function argument javascript
(2 answers)
Closed 8 years ago.
I am building a function to match types of variables. It will be an alternative to typeof <var> === "something".
My function call looks like this : is("some text")["string"]. It returns true, or is([])["element"]. Now it returns false, But I have an issue with it.
For example, if I try to send an undefined variable like "undefVar" to a function I am expecting something like this: is(undefVar)["undefined"], but I get an error which says that "undefVar" is not defined.
Can I somehow make my function work using undefined variables? Is this possible at all?
p.s: I have to use this function a lot so it seems (for me) that it would be better to use something like this : is(var)[type] as opposed to typeof var === type.
typeof is special on nonexistent variables. You cannot mimic it with a function.
No, you cannot blindly pass undefined variables to your function from the call site and globally change the behavior of the JS engine to accomodate this.
typeof is a built-in operator and is not bound by the rules of "common" functions, which is why it can do things that custom functions cannot.
Finally, I strongly disagree that it would be practically preferable to use an alternative syntax even if that were possible.

Categories