title: Regex to change a html element class with javascript not working
body: <p>I have the following javascript function to open and close sub list elements on an onclick event:</p>
  
  <pre><code>function ShowHideDtls(itId) {
      var subMen = document.getElementById(itId);
      if (subMen != null) {
          if (subMen.className == "nav nav-second-level collapse in") {
              subMen.className = "nav nav-second-level collapse";
          } else {
              subMen.className += " in";
          }
      }
  }
  </code></pre>
  
  <p>The "collapse" is a css class which makes display=none hiding the sub list and "in" is a class which makes display=block showing the sub list, creating a menu with submenus.</p>
  
  <p>I found in this question <a href="https://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript">Change an element's class with JavaScript</a> in the first(accepted) answer use of a regex in order to do this. I tried it like this:</p>
  
  <pre><code>function ShowHideDtls(itId) {
      var subMen = document.getElementById(itId);
      if (subMen != null) {
          if (subMen.className.match(/(?:^|\s)in(?!\S)/)) {
              subMen.className.replace(/(?:^|\s)in(?!\S)/g, '');
          } else {
              subMen.className += " in";
          }
      }
  }
  </code></pre>
  
  <p>The code without the regex works perfectly but with the regex it doesn't. I checked the regex in regex101.com and it seems to work there. As I understand it's more appropriate to use the regex than a long string of all the class names and also I also have a nav-third-level class that I have to close and open so the regex seems to be the convenient and proper way to do it.
  What's wrong?
  Thank you.</p>