473,396 Members | 1,938 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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(str));
}
</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 2646

<ja*********@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.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(str));
}
</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*********@gmail.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(str));
} 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 = "balabaliolopaliouliap";
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.prototype.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/rasterTriangleDOM.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
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:...
10
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...
5
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...
3
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...
8
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...
11
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;...
6
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:...
4
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'...
4
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
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,...
0
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...
0
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...
0
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...
0
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,...

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.