Jump to content

Regexp String Test()


jpittbull

Recommended Posts

I'm trying to search a string for a left angle bracket "<" but am getting some odd results. If the "<" is followed by a character, the string disappears. If it is followed by a space the string prints just fine. Does anyone know what's going on with the "<". I don't have control over the input so I can't modify it in any way. Put this in the "Tryit Editor":This one works fine.

<html><body><script type="text/javascript">var patt1=new RegExp("<");var str="This< is a short string";document.write(str  +  "<br>");document.write(patt1.test(str));</script></body></html>

The results:The results:[This< is a short stringtrue

<html><body><script type="text/javascript">var patt1=new RegExp("<");var str="<This is a short string";document.write(str  +  "<br>");document.write(patt1.test(str));</script></body></html>

Results:true Notice the string didn't print.This one is even odder. It causes the return value of test() to have strikethrough.

<html><body><script type="text/javascript">var patt1=new RegExp("<");var str="This i<s a short string";document.write(str  +  "<br>");document.write(patt1.test(str));</script></body></html>

Link to comment
Share on other sites

Place the JavaScript in a separate file or escape all "<" as HTML entities, i.e. <, like:

<html><body><script type="text/javascript">var patt1=new RegExp("<");var str="This< is a short string";document.write(str  +  "<br>");document.write(patt1.test(str));</script></body></html>

The reason this is happening is because HTML gets parsed before JavaScript. What the browser thinks when reading "<" is "an element is about to start. The next characters up until the next space identify its name". Only once HTML is parsed does the browser see the RegExp object, and considers the string between the quotes as the regular expression. By that time, the < is turned into "<", which is what the JavaScript interpreter sees.

Link to comment
Share on other sites

Thanks for your insight regarding html getting parsed before javascript. Didn't know that. I got it working without putting the script in a seperate file. I send the value of the text field directly to the function. Here's a simplified version:

<html><script type="text/javascript">function validate_firstname() {  alert("validate firstname " + document.getElementById("firstname").value);  var ptrn=new RegExp("[><]");  if (ptrn.test(document.getElementById("firstname").value)) {    alert("Do not use angle brackets");  }  else{    alert("Looks good");}}</script><body><form action="">First name: <input type="text" name="firstname" onblur="validate_firstname()"></form></body></html>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...