This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 3 years ago.
I have a weird situation. I am using a Regex testing some strings. I would like to seal them to a class, like the following:
export class RegexPattern {
static price = (/^\d*(\.\d{1,2})?$/g);
static phone = (/^([0-9]{0,5}-)?[0-9]{10}$/g);
}
So lets say the input is '32'
But when I use it to test same strings twice, the first time will pass, the second time will fail, eg:
RegexPattern.price.test('32') //return ture
RegexPattern.price.test('32') // return false
But if I use it with bare Regex, without sealing:
(/^\d*(\.\d{1,2})?$/g).test('32') //return ture
(/^\d*(\.\d{1,2})?$/g).test('32') // return true
My question is why did this happen?
The RegExp object keeps track of the lastIndex where a match occurred, so on subsequent matches it will start from the last used index, instead of 0.
If you don't want to manually reset lastIndex to 0 after every test, just remove the g flag.
When you test the regex individually, you're actually creating a new regexp object with every invocation, that's why that works. If you were doing:
'use strict';
const regex = /^\d*(\.\d{1,2})?$/g;
console.log(regex.test(32));
console.log(regex.test(32));
You would get true, false, too.
Related
This question already has answers here:
JavaScript expressions, comma delimited within parentheses [duplicate]
(3 answers)
Closed 2 years ago.
I was going through documentation of JavaScript about arrays and objects.I found one unique query about arrays
var a= [1,2,3]
console.log(a) // give [1,2,3]
var b = [(1,2) , (3,4) , (5,6)]
console.log(b) // gives [2,4,6]
I didn't understand the logic behind the same.It just ran over my mind.If we do same thing in python
a = [(1,2),(3,4)]
print(a) // [(1,2),(3,4)]
Can some one explain the same and can someone explain me how to get the same output in JavaScript like the way I got in python.How to iterate through all the elements in array in javascript
I'm not a Python programmer, but those parentheses differ in their functionality between Python and JavaScript.
I understand in Python they indicate a tuple literal. In JavaScript, they merely group things they say "execute each statement and return the last one." That's why you only see some items in your JS arrays.
See also https://stackoverflow.com/a/25280412/1371131
What you have encountered is the comma operator.
When there is no other context, a , in an expression behaves like an operator just like + or = or / etc.
The comma operator behaves as follows:
evaluate the first expression
ignore the result of the first expression
evaluate the second expression
return the value of the second expression
Thus the following code:
a = 1,2;
b = 1,2,3,4;
will result in a being assigned the value 2 and b assigned the value 4.
This may seem kind of silly because we already have ; but the comma operator is useful if you need more than one thing to happen in a single expression context. For example if you need more than one thing to happen in one of the conditions of a for loop you cannot use ; because that is used to separate the conditional expressions. The comma operator comes to the rescue:
for (let a = 0, b = 0; a < 10; a++, b++) { //...
// ^ ^
// | |____ two things happen here
// |_______________________________ and here
So (1,2) is just another way to write 2.
Therefore [(1,2) , (3,4) , (5,6)] and [2,4,6] is the same array.
Just like [1+1, 2+2, 3+3] and [2,4,6] is the same array.
They are just different ways to write [2,4,6]. The same way you cannot loop through the array and extract 1+ from [1+1, 2+2, 3+3] you cannot loop through the array and extract (1, from [(1,2) , (3,4) , (5,6)].
If you really need an array of pairs you need to use an array of arrays:
a = [[1,2],[3,4],[5,6]]
This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 6 years ago.
This is related to the arrays in Javascript, which I am trying to use in a complex logic.
Consider the following code:
a['a1'] = 'AJA'
We know that, this is same as a.a1 = 'AJA' (provided proper definitions were given).
So, if we go ahead and interpret this:
console.log(a.a1[0])
console.log(a.a1[1])
console.log(a.a1[2])
console.log(a.a1)
It logs :
A
J
A
AJA
Now, all I need is to assign a new character at the 4th position.
When I try a[a1][3] = 'Y' or a.a1[3] = 'Y' and then try console.log(a.a1), It still displays AJA instead of AJAY.
I know that we can do this using string concatenation, i.e.
a['a1'] = a['a1'] + 'Y' and get this accomplished.
But why wasn't the first method working? By what other ways can do this?
Strings are immutable. It means that if you create a string, you can't modify it anymore. So your a1 doesn't know anything about 4th character.
You can see this example. I try to change the second char of the already created string, but it will not be changed anymore.
let a = {};
a['a1'] = 'AJA';
a.a1[1] = 'A';
console.log(a.a1);
For more you can see MDN Documentation
As I know a[a1][3] or a.a1[3] is a string variable, you can treat it as:
var s = 'ss';
When you evaluate s[0] you'll get a string value. So when you assign any string value to s, you'll not get 'ss' + anyvalue but anyvalue instead. :)
This question already has answers here:
Do common JavaScript implementations use string interning?
(3 answers)
Closed 7 years ago.
In some languages, frequently used strings are defined as variables/constants, which are called instead of literal strings. Is this the same with JavaScript? In particular, I have frequent use of the string 'none'. Instead of writing the literal 'none' everywhere in the code, would it improve performance if I define:
var none = 'none';
and use none everywhere in the code? Or, is there a way to intern a literal string expression so that it is evaluated only once?
Literal strings are automatically interned by most Javascript compilers. So var a = 'hello' and var b = 'hello' will likely already be pointing at the same copy of the 'hello' string in memory, no need for further optimization on your part.
The only way to make sure different string objects are created for the same string value is by defining each one via the String global object, i.e.:
var a = new String('hello');
var b = new String('hello');
This question already has answers here:
What characters are valid for JavaScript variable names?
(12 answers)
Closed 7 years ago.
I am coding a scientific calculator and I need some help:
function √(in){
return Math.sqrt();
}
// throws an error
var √ = function(in){
return Math.sqrt();
}
// also throws an error
var √ = "sqrt";
√randomSqNum = 100,
√random = {sqrt:4,cubert:8},
√sqNum = ["0","1","4","9","16","25"],
√null = null,
√undefined = undefined;
They all throw an error!
Please explain why they throw an error.
Also, Is there a way around this?
In Javascript, variable names must begin with a letter, _ or $. More information here:
http://www.w3schools.com/js/js_variables.asp
JavaScript follows annex 31 of the unicode standard regarding identifier names.
I assume you are using U+221A as character. As you can see from the linked page, it can neither be used at the beginning of an identifier nor within it:
(likely because it is not even a letter).
Compare that to π, which is a letter and which can be used in an identifier name.
Also, Is there a way around this?
No. However, you can always try to find letters that look similar.
You cannot use it directly as a name, but you can use it as key.
var f={}
f["√"] = Math.sqrt
alert(f["√"](5))
In such way you can define +-*/ and many other funcions.
f["+"] = function(a){
return a.reduce(function(p,v){
return p+v
},0)
}
And when you have a parsed statement tree in form {o:fn,a:[s1,...,sn]} where fn is function name and s1,...,sn are subtrees or values, then you can simply get the result:
function calc(st){
return (typeof st == 'object')?f[st.o].apply(null,st.a.map(calc)):st
}
This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 9 years ago.
I have this simple pattern that validate Time - 24 Hours Mode -
var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g;
If i execute this pattern with .test() method twice i get two different values
Like This
CODE
console.log(patt.test('01:09')); // true
console.log(patt.test('01:09')); // false
i have notice that if i do the following i get the same result :
var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g;
console.log(patt.test('01:09')); // true
var patt = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/g;
console.log(patt.test('01:09'));//true
Question
i'll re-initiate the patt object as a work around in my case but i'm very curious to know what happens
Also i notice that patt object doesn't change after using it with test() Method
jsFiddle for those how want to prove something
Remove the global flag. Currently it's searching at the end of your input string for the second time, where it won't find the pattern again. See docs for the lastIndex property.