Why is the JavaScript RegExp.test() method behaving as a toggle? [duplicate] - javascript

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 6 years ago.
Can anyone explain why the alert() in the following JavaScript code is firing? It appears to be a bug in the RegExp.test() method which reverses its previous decision each time you run the method. I'm using IE7.
I've found a replacement that appears solid, using the string.search(regex) method instead. But, I'm curious whether anyone knows something about this.
var styleHasWidthRegex = /\bwidth\s*\:/ig;
var styleText = "WIDTH: 350px";
var result1 = styleHasWidthRegex.test(styleText);
var result2 = !styleHasWidthRegex.test(styleText);
if (result1 == result2) {
alert("This should never happen!");
}

Your regex has the global (g) flag set. Every time it is executed, it'll update an internal index (the lastIndex property) specifying where it left off, and begin searching at that point the next time through.
Of course, you don't really want that - you want it to start at the beginning every time. So ditch the g flag.
See also: Inconsistent javascript logic behavior

In this scenario, you should be needing a global tag anyways, since in css declarations a property should only be declared once.

Related

I’m having trouble creating dynamic variables with Window in JavaScript [duplicate]

This question already has answers here:
How do I create dynamic variable names inside a loop?
(8 answers)
Create dynamic variable names based on count result
(3 answers)
Closed 3 months ago.
I am trying to create dynamic variables using Window. The exact thing I want to do is working fine with eval. But as you may know, that’s not advised.
Some examples.
I may define some variables like this.
var word1 = The;
var word2 = Number;
var word3 = Is;
var number = 100;
Now I combine them.
var phrase = word1+word2+word3+number.
If I use the window keyword in front of the phrase variable, then it will work, provided it is at the beginning of the line of code. However, if I try to put window in front of a variable in the middle of a line of code, it doesn’t work. However, eval does work. Example below.
window[phrase]
That will work.
But if it’s something like this
window[newCombinedVariable] = document.querySelector(window[newCombinedVariable2])
That will not work.
However, this will work.
window[newCombinedVariable] = document.querySelector(eval(newCombinedVariable2))
So, window can take a combination of strings with dynamic variables and it works at the beginning, but not in the middle, such as after doc/query selector. But eval works fine that way when using the exact same combined variables.
Can someone suggest what I must do in order for window to give me the same results as eval?

How does the functions differ from objects in Javascript? [duplicate]

This question already has answers here:
Set document.getElementById to variable
(5 answers)
Closed 5 years ago.
I have this habit of using function id(_id) { return document.getElementById(_id); } as to lessen the work of typing this over and over.
sidenote:
jquery becomes too heavy for small tasks and projects
As I learnt Javascript more I came to know that we can pass around functions just like objects so we can do
var id = document.getElementById;
It seems like both do the exact same thing. However, I am not an expert in Javascript, so could there be any difference internally? and which is the preferred way of using?
Yes, the context is:
const log = console.log;
log("test");
The upper wont work because the context changed, and log must be called on a console object, not on window ( aka without context). However, there are easy workarounds:
const log = console.log.bind(console);
Or you use functions, for example the arrow ones:
const log = (...args) => console.log(...args);

significance of javascript:void(0) returning "undefined" [duplicate]

This question already has answers here:
What does "javascript:void(0)" mean?
(14 answers)
Closed 8 years ago.
I have more than a few doubts regarding javascript:void(0).
the following are my doubts.
I know it returns "undefined" but what is the significance of it. Or in other words, at what sitiation or circumstance do we use javascript:void(0); what exactly does the programmer want when he uses javascript:void(0)
I'm asking this question because i dont have a clear understanding of javascript:void(0) and it might be stupid. But what would happen if i use javascript:myFunction("some argument") instead.
like for example
please focus more on the second part.
say if you put
Hii
and when you will click the url, you will see # getting appended to the url
but if we put href="javascript:void(0);" that means we are calling a void javascript function.
It wont append # at the end of url.
The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).
Also if you put
Huii
then if u see in console it will tell you myFunction() is not defined.

do I need eval? [duplicate]

This question already has answers here:
Why does eval() exist?
(6 answers)
Closed 9 years ago.
I've searched the web for what eval does and here is what I have found:
The eval() method evaluates JavaScript code represented as a string.
And I've read this question, which says that it is evil.
But I really don't understand what does it do, i.e I don't see when to use eval.
I mean:
var x= 3;
var y =5;
var z = eval("x+y");
// is the same as:
var z = x+y;
so as I see it's just adding characters to my code. Can somebody give me an example of why eval was created in the first place?
It allows execute dynamicly generated code, not just "x+y".
Eval allows you to evaluate a string as javascript code. This means you can do things like evaluate a string to call a function:
function add(x,y){
return (x+y);
}
stringToEval = 'add(5,6)';
eval(stringToEval);
This code would run the function by evaluating the string as a function call.
So I would say you do not need to use eval here. Just add the two variables.

Is JavaScript test() saving state in the regex? [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 7 years ago.
Open up a browser console and execute the following code:
var foo = /foo/g;
Then,
foo.test("foo") // true
Then,
foo.test("foo") // false
If you continue to execute foo.test("foo"), you will see alternating true/false responses as if the var foo is actually being modified.
Anyone know why this is happening?
Yes, that's how .test() and .exec() work when the regex is g global. They start at the end of the last match.
You can observe the current last index on the regular expression object using the .lastIndex property.
It's a writeable property, so you can reset it to 0 when/if you need. When the regex is run without finding a match, it automatically resets to 0.
The regex keeps the position of the last test. This allows searching of long strings. You can reset this by setting lastIndex = 0;

Categories

Resources