title: Javascript Regex restrict underscore at start and end
body: <p>I have a form where I want to restrict first and last characters. (javascript)
  Restriction is:</p>
  
  <ul>
  <li>Input must start and end with alphanumeric, not underscore while just underscore is allowed in between alphanumeric. </li>
  </ul>
  
  <p>Examples:</p>
  
  <pre><code> Valid Entries: abc, ABC, Abc123, 123a, Abc_12, Abc_12_3a
   Invalid Entries: _abc, abc_, _abc_
  </code></pre>
  
  <p>I tried to create my regex as below:</p>
  
  <pre><code>^(?!\_)(?!_*_$)[a-zA-Z0-9_]+$
  </code></pre>
  
  <p>This does not allow underscore at the start which is fine but does allows underscore at the end which I want to restrict.</p>
  
  <p>Any inputs whats missing here.</p>
  
  <p>Thanks</p>
  
  <hr>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const validEntries = ['abc', 'ABC', 'Abc123', '123a', 'Abc_12', 'Abc_12_3a'];
  const invalidEntries = ['_abc', 'abc_', '_abc_'];
  
  const regex = /^(?!\_)(?!_*_$)[a-zA-Z0-9_]+$/;
  
  validEntries.forEach((x) =&gt; {
    const ret = regex.test(x);
    
    console.log('Should be true :', ret);
  });
  
  console.log('-------------------');
  
  invalidEntries.forEach((x) =&gt; {
    const ret = regex.test(x);
    
    console.log('Should be false :', ret);
  });</code></pre>
  </div>
  </div>
  </p>
  
  <p>---Updated---</p>
  
  <p>I am using the regex in my angularjs application.</p>
  
  <p>I have created my directive as:</p>
  
  <pre><code>       .directive('restrictField', function () {
      return {
          require: 'ngModel',
          restrict: 'A',
          link: function (scope, element, attrs, ctrl) {
  
              var regReplace,
                  preset = {                   
                      'alphanumeric-spl': '\\w_./\s/g',
                      'alphanumeric-underscore': '\\w_',
                      'numeric': '0-9',
                      'alpha-numeric': '\\w'
                  },
                  filter = preset[attrs.restrictField] || attrs.restrictField;                
  
              ctrl.$parsers.push(function (inputValue) {
                  regReplace = new RegExp('[^' + filter + ']', 'ig');
                  if (inputValue == undefined)
                      return ''
                  cleanInputValue = inputValue.replace(regReplace, '');
                  if (cleanInputValue != inputValue) {
                      ctrl.$setViewValue(cleanInputValue);
                      ctrl.$render();
                  }
                  return cleanInputValue;
              });
          }
      }
  })
  </code></pre>
  
  <p>I am using this in my html as:</p>
  
  <pre><code> &lt;input type="text" name="uname" ng-model="uname" required class="form-control input-medium" restrict-field="alphanumeric-underscore" ng-trim="false" /&gt;  
  </code></pre>