Jump to content

Javascript RegExp working only on odd rows?


JacekQ

Recommended Posts

Hello, I'm trying to hide/show table rows using RegExp. And I don't know why I have to create RegExp for each row. This is my script:

<!DOCTYPE html><html><body> <table border="1"><tr><td name="c1">row1 col1</td><td name="c2">row1 col2</td></tr><tr><td name="c1">row2 col1</td><td name="c2">row2 col2</td></tr><tr><td name="c1">row3 col1</td><td name="c2">row3 col2</td></tr><tr><td name="c1">row4 col1</td><td name="c2">row4 col2</td></tr><tr><td name="c1">row5 col1</td><td name="c2">row5 col2</td></tr></table> <button onclick="myFunction()">Try it</button> <script>function myFunction(){var c = document.getElementsByName('c1');var re = new RegExp('row', 'ig');var display = 'none';var parent;for(var i = 0; i < c.length; i++){  parent = c[i].parentNode;  var display = 'none';  // re = new RegExp('row', 'ig');  if(re.test(c[i].innerHTML))  {	display = 'table-row';  };  parent.style.display = display;};}</script> </body></html> 

And when I click button the even rows disappear but should not.It works fine when I uncomment re = new RegExp('row', 'ig'); in loop.Why I have to create regexp for each step in loop? --Best regardsJacek Q.

Link to comment
Share on other sites

That's caused by the g modifier. The regular expression uses an internal pointer when you have it search globally. After the first match the pointer is set to the position after the match, so when you call test again it starts looking from that point. If you always want it to start looking from the start them remove the g modifier. You would think the internal pointer would get reset if it is testing a different string, but apparently not.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...