473,664 Members | 3,066 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does JavaScript Regx behave weirdly?

A very simple regular expression test:

var regx = /^\d+$/g;
alert(regx.test ("11") + ": " + regx.test("11") );

And the output is "true: false".

If I change to regx = new RegExp("^\\d+$" , "g");
Then the output is the same.

This is the first weird part.

The second weird part is, when I only test the string once in a
function:

var regx = /^\d+$/g;
alert(regx.test ("11") + ": ");

var regx = new RegExp("^\\d+$" , "g");
alert(regx.test ("11") + ": ");

If I call the function twice, the output will be

1st call:
true, true

2nd call:
true, false

My assumption is the global expression holds an internal status, but
that doesn't explain the second example.

Can someone help me out here please?

Sep 22 '08 #1
3 1623
Cain <st***********@ gmail.comwrites :
A very simple regular expression test:

var regx = /^\d+$/g;
alert(regx.test ("11") + ": " + regx.test("11") );

And the output is "true: false".
Expected behavior. When you use the "g" flag, the regexp remembers the
position end of its match, and tries to match from that point when its
"test" or "exec" methods are next called. It does so until it fails to
match, at which point it resets itself so the next invocation will start
at position 0 again.

The second weird part is, when I only test the string once in a
function:

var regx = /^\d+$/g;
alert(regx.test ("11") + ": ");

var regx = new RegExp("^\\d+$" , "g");
alert(regx.test ("11") + ": ");

If I call the function twice, the output will be

1st call:
true, true

2nd call:
true, false
Your output doesn't match what you wrote above.

Anyway: A regexp literal (/whatnot/) creates only one RegExp instance,
even if it occurs inside a function. Not once each time the function
is called. Since the regexp literal has the "g" flag, the same case
as above occurs.

My assumption is the global expression holds an internal status, but
that doesn't explain the second example.
It does :)

/L
--
Lasse Reichstein Nielsen
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Sep 22 '08 #2
Cain wrote:
[...]
var regx = /^\d+$/g;
alert(regx.test ("11") + ": " + regx.test("11") );

And the output is "true: false".
[...] when I only test the string once in a function:

var regx = /^\d+$/g;
alert(regx.test ("11") + ": ");

var regx = new RegExp("^\\d+$" , "g");
alert(regx.test ("11") + ": ");

If I call the function twice, the output will be

1st call:
true, true

2nd call:
true, false
[...]
Evidently, you have not been paying attention:

<48************ **@PointedEars. de>
(Fri, 19 Sep 2008 01:50:43 +0200)

<67************ *************** *******@a70g200 0hsh.googlegrou ps.com>
(Mon, 22 Sep 2008 07:15:23 -0700 (PDT))

See also <http://www.jibbering.c om/faq/#FAQ2_3>.
PointedEars
--
var bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.js:16
Sep 22 '08 #3
Thank you for the wonderful explanation:)
I have been struggling on this for so many days, and couldn't find a
reasonable explanation on the internet.
Thanks a million~
Sep 22 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
3600
by: Andrea | last post by:
Hi everyone, I am in the process of learning javascript and have a question on location.href. Does javascript always require the <script language = "javascript"> (or script type="text/javascript">) to run? I'm asking because the following chunk of code (drop down menu that goes to different parts of the page) works without declaring anywhere that it's javascript:
11
2013
by: Saqib Ali | last post by:
Please excuse me, this is a fairly involved question that will likely require you to save the file below to a file and open it in a browser. I use Mozilla 1.5, so the problem I describe below should be reproducible with that version at least. BACKGROUND: =========== When you open this page in your browser, you will see a 4 cell table. The cells contain the following items respectively:
3
1842
by: Dietmar Prantner | last post by:
Hello, I tried a Javascript on my homepage that works fine on Netscape, works nearlyx normal on Opera but does not work at all on Internet Explorer. Is there anybody out there who can help? I use a frameset of 3 frames. One of these Frames has thumbnails with the javascript code for the image-swap - the big picture should change whenever someone clicks on the corresponding thumb. IE does not do anything if you click on a thumb - and...
19
1812
by: tnhoe | last post by:
Hi, any excel like grid javascript which is stable and fast to load thousand of rows data ? can it have F2 function to popup another window ? can validate cell value when cursor move away that cell ? Either free or low developer license with royalty-free distributed with web application. TQ. Regards Hoe tnhoe@pc.jaring.my
6
6322
by: luckyjameel | last post by:
Hi Guys Hope this message shall find u all in gr8 moods. As i was developing a Application for Online Exam and i am in need of a way to maintain the time for the logged in user. So Can any one let me know how can i do this with the help of JavaScript. Regards Lucky
1
1202
by: Glenn Wilson | last post by:
Can anyone help me with a regx to match the values 1 to 6. No these could come in several formats and we only want matches where there is a single number with no other numbers next to it in the string, We could have an alpha beside it on either side though Examples of matches 1 2 3
6
1349
by: Jake Barnes | last post by:
This function has always worked for me just fine: function nl2br_js(myString){ // 02-18-06 - this function imitates the PHP command nl2br, which finds newlines in a string // and replaces them with newlines plus HTML BR tags. Is the easiest way to create the // appearance of paragraphs when people are creating web pages by typing text into a form. var regXString = "\\n"
1
1521
by: jain236 | last post by:
Hi i am trying to write regx for the time format HH:MM:SS in the below way /\d:\d0:\d/ but i could not get the desired output, can some one throw some light why and where it is going wrong? Thanking you in advance
0
8437
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8861
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8778
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7375
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5660
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4185
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2764
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1759
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.