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.
Related
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.
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:
Javascript Regexp dynamic generation from variables? [duplicate]
(4 answers)
Closed 7 years ago.
I'm looking for a working solution with dynamic regex in Javascript.
this solution works for me: (but is not dynamic)
new RegExp(\bal\i);
but this solution is not working:
var value = 'bal';
new RegExp('\'+value+'\i');
Could anyone help me how to adjust it to make it work? Thank you
you can pass the string (value) in the RegExp constructor, along with the ignoreCase flag as:
var value = 'bal';
var b = new RegExp(value, 'i')
b.test('BAL')
it returns true.
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.