JavaScript regex multiline flag doesn't work

前端 未结 5 1735
清酒与你
清酒与你 2020-11-22 09:41

I wrote a regex to fetch string from HTML, but it seems the multiline flag doesn\'t work.

This is my pattern and I want to get the text in h1 tag.

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:22

    My suggestion is that it's better to split the multiple-line string with "\n" and concatenate the splits of the original string and becomes a single line and easy to manipulate.

    
    
    
    $( document ).ready( function() {
      var errorMessage = "Please match the requested format.";
      var firstVisit = false;
    
      $( this ).find( "textarea" ).on( "input change propertychange", function() {
    
        var pattern = $(this).attr( "pattern" );
        var element = $( this );
    
        if(typeof pattern !== typeof undefined && pattern !== false)
        {
          var ptr = pattern.replace(/^\^|\$$/g, '');
          var patternRegex = new RegExp('^' + pattern.replace(/^\^|\$$/g, '') + '$', 'gm');     
    
          var ks = "";
          $.each($( this ).val().split("\n"), function( index, value ){
            console.log(index + "-" + value);
            ks += " " + value;
          });      
          //console.log(ks);
    
          hasError = !ks.match( patternRegex );
          //debugger;
    
          if ( typeof this.setCustomValidity === "function") 
          {
            this.setCustomValidity( hasError ? errorMessage : "" );
          } 
          else 
          {
            $( this ).toggleClass( "invalid", !!hasError );
            $( this ).toggleClass( "valid", !hasError );
    
            if ( hasError ) 
            {
              $( this ).attr( "title", errorMessage );
            } 
            else
            {
              $( this ).removeAttr( "title" );
            }
          }
        }
    
      });
    });
    

提交回复
热议问题