473,573 Members | 4,181 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

RegExp.test() funkiness (fails every second call)

Just a heads up for anybody that comes across this in the future.

Noticed a strange behavior in RegExp.test() today. Check out the
following code. It will alternately display "chokes" and null, as
every second call to .test() fails.

<script>
var str = "RegExp (chokes) on this every 2nd time";
var re = /chokes/g;

for (var a=0; a<10; a++)
{
alert(re.exec(s tr));
}
</script>
Remove the "g" from the end of the RegExp and it works as expected.
The "g" switch instructs the regex to perform global matching, which
shouldn't affect the testing for a single run. Anybody care to venture
an explaination for why this might have the demonstrated effect?
Jason Kester
Expat Software Consulting Services
http://www.expatsoftware.com/

Oct 1 '05 #1
3 2671

<ja*********@gm ail.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Just a heads up for anybody that comes across this in the future.

Noticed a strange behavior in RegExp.test() today. Check out the
following code. It will alternately display "chokes" and null, as
every second call to .test() fails.

<script>
var str = "RegExp (chokes) on this every 2nd time";
var re = /chokes/g;

for (var a=0; a<10; a++)
{
alert(re.exec(s tr));
}
</script>
Remove the "g" from the end of the RegExp and it works as expected.
The "g" switch instructs the regex to perform global matching, which
shouldn't affect the testing for a single run. Anybody care to venture
an explaination for why this might have the demonstrated effect?
Jason Kester
Expat Software Consulting Services
http://www.expatsoftware.com/


From the Windows Script Technologies help file:

If the global flag is set for a regular expression, exec searches the string
beginning at the position indicated by the value of lastIndex. If the global
flag is not set, exec ignores the value of lastIndex and searches from the
beginning of the string.
Oct 1 '05 #2
ja*********@gma il.com writes:
It will alternately display "chokes" and null, as
every second call to .test() fails.

<script>
(should have type="text/javascript" attribute :)
var str = "RegExp (chokes) on this every 2nd time";
var re = /chokes/g;
for (var a=0; a<10; a++)
{
alert(re.exec(s tr));
} Remove the "g" from the end of the RegExp and it works as expected.
As some people would expect, yes (but not the ones who have read the
ECMAScript specification (and remembers it, that's the hard part :) )
The "g" switch instructs the regex to perform global matching, which
shouldn't affect the testing for a single run.
It should. This is what allows you to do global matching in steps, with
computation in between, e.g.:
---
var string = "balabaliolopal iouliap";
var re = /[aeiou]/g;
var match;
var count = {};
while(match = re.exec(string) ) {
var vowel = match[0];
count[vowel] = (count[vowel] || 0) + 1;
alert("Vowel "+vowel+" found at index " + (re.lastIndex)) ;
}
---
Anybody care to venture an explaination for why this might have the
demonstrated effect?


Because a call to RegExp.prototyp e.exec with a regular expression with
the global flag set will start matching from the regexp's current
value of lastIndex - the index of the previous match. Only when the
exec fails to do a match will lastIndex be reset to 0.

You can add a line:
re.lastIndex = 0;
before each call, if you only want to find the first match.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Oct 1 '05 #3
===
(should have type="text/javascript" attribute :)
===

In order to validate for the w3c parser. But only in order for that.
For the rest it will work, also if failing validation, no human will
ever notice, no browser will ever complain, no version of browsers will
fail to understand it.
This at least until that very happy day shall come when a browser will
FINALLY utterly refuse to parse a script because it lacks the type, and
shall send all awry in the name of w3c strict validation. Till that
very very happy time, we can omit it with sheer awful impunity and go
to no jail despite the abominable crime LOL :-)

Ah yeah, spreading good programming practice & "quality assurance"...
right I forgot :-)

ps no ad personam/hominem/guy provocation meant, really. It's just that
with all these pages failing validation for these nuisances, we at
times get the impression that when dealing wsith the w3c parsers we are
like Romeo and Juliet in Shakespeare:

===
peace, peace, mercutio, peace! thou talk'st of nothing.
===

No type parser, no type; failed validation!! but peace, peace, parser,
peace! thou talk'st of nothing. :-)

I am afraid I shall miss the following harrowing explanation (not by
you, I know you meant it with a dash of humour), full of rage and fury
and signifying nothing, about the outermost importance of the type and
of the strict validation and of how much of an incredible hopeless
crooked disgusting moron and despicable blackguard I am to vilify such
an important momentuous pivotal thing like the type attribute in the
script tag.... :)

ciao
Alberto
http://www.unitedscripters.com/

Oct 9 '05 #4

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

Similar topics

10
39337
by: Anand Pillai | last post by:
To search a word in a group of words, say a paragraph or a web page, would a string search or a regexp search be faster? The string search would of course be, if str.find(substr) != -1: domything() And the regexp search assuming no case restriction would be,
10
7672
by: Andrew DeFaria | last post by:
I was reading my O'Reilly JavaScript The Definitive Guide when I came across RegExp and thought I could tighten up my JavaScript code that checks for a valid email address. Why does the following not appear to work: var email_address = "Joe@Schmoe"; var email_regex = new RegExp ("^(\\w+)(\@)(\\w+)(\.)(\\w+)$"); var result = email_regex.exec...
5
2044
by: Syed Ali | last post by:
Hello, I am trying to create a regexp to express non letters and space. I tried using: var myreg = new RegExp (""); However, it is not working. Basically I want to allow only words with letters in a textfield, space is ok, but no special characters such as $%^ or numbers such as
3
1707
by: Sped Erstad | last post by:
There must be a simple regexp reason for this little question but it's driving me nuts. Below is a simple regexp to determine if a string contains only numbers. I'm running these two strings through the two very subtly different pieces of code: "0" and "0a" If I do the two "nots" on it, it works perfectly ("0" succeeds, "0a" fails). ...
8
2013
by: Dmitry Korolyov | last post by:
ASP.NET app using c# and framework version 1.1.4322.573 on a IIS 6.0 web server. A single-line asp:textbox control and regexp validator attached to it. ^\d+$ expression does match an empty string (when you don't enter any values) - this is wrong d+ expression does not match, for example "g24" string - this is also wrong ...
11
2916
by: HopfZ | last post by:
I coudn't understand some behavior of RegExp.test function. Example html code: ---------------- <html><head></head><body><script type="text/javascript"> var r = /^https?:\/\//g; document.write( ); </script></body></html> ---------------------
6
1391
by: Christian Sonne | last post by:
Long story short, I'm trying to find all ISBN-10 numbers in a multiline string (approximately 10 pages of a normal book), and as far as I can tell, the *correct* thing to match would be this: ".*\D*(\d{10}|\d{9}X)\D*.*" (it should be noted that I've removed all '-'s in the string, because they have a tendency to be mixed into ISBN's) ...
4
3892
by: Matt | last post by:
Hello all, I have just discovered (the long way) that using a RegExp object with the 'global' flag set produces inconsistent results when its test() method is executed. I realize that 'global' is not an appropriate modifier for the test() function - test() searches the entire string by default. However, I would expect it to degrade...
4
2528
by: r | last post by:
Hello, It seems delimiters can cause trouble sometimes. Look at this : <script type="text/javascript"> function isDigit(s) { var DECIMAL = '\\.'; var exp = '/(^?0(' + DECIMAL
0
7789
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...
0
8037
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. ...
0
8215
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...
0
8086
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5605
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3737
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...
0
3743
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1325
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1048
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...

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.