Cannot read property 'length' of null in j

2019-07-05 05:49发布

问题:

I'm trying to make a markdown editor like Stack Overflow has.

I get this error listed in the title if I don't actually type an asterisk AND a http:// containing phrase into the textarea. If I only type an asterisk containing phrase, the error refers to this line: if(linkify.length!==0)

Here's a jsfiddle to show you what I mean.

Here's my HTML:

<textarea></textarea>
<div></div><button type="button">Markdownify</button>

Here's my JS:

var val=$('textarea').val(), boldify = val.match(/\*\*[A-Za-z0-9]+\*\*/gim),
italicify = val.match(/\*[A-Za-z0-9]+\*/gim),linkify = val.match(/http\:\/\/[A-z0-9]+\.[A-z0-9]+/gim);

$(document.body).on('click', 'button', function() {

val=$('textarea').val(), boldify = val.match(/\*\*[A-Za-z0-9]+\*\*/gim),
italicify = val.match(/\*[A-Za-z0-9]+\*/gim),linkify = val.match(/http\:\/\/[A-z0-9]+\.[A-z0-9]+/gim);

if (boldify.length!== 0){
            for (var i=0; i < boldify.length; i++)  {
                var boldMatch= boldify[i],  
                boldReplace = boldMatch.replace(/\*\*[A-z0-9]+\*\*/gim, '<span style="font-weight:bold;color:blue;">'+boldMatch+'</span>'),
                val = val.replace(boldMatch, boldReplace);     
            }
        val = val.replace(/\*\*/gi, "");
}

if(italicify.length!== 0){
    for(var j=0; j < italicify.length; j++){
    var italicMatch= italicify[j],
     italicReplace = italicMatch.replace(/\*[A-z0-9]+\*/gim, '<span style="font-style:italic;color:red;">'+italicMatch+'</span>');
    val = val.replace(italicMatch, italicReplace); 
    }
    val = val.replace(/\*/gi, "");
}

if(linkify.length!== 0){
    for(var k=0; k < linkify.length; k++){
    var linkMatch= linkify[k],
    linkReplace = linkMatch.replace(/http:\/\/[A-z0-9]+\.[A-z0-9]+/gim, '<a href="'+linkMatch+'">'+linkMatch+'</a>');
        val = val.replace(linkMatch, linkReplace);
    }
}

$('div').html(val);
});

Any help would be greatly appreciated.

回答1:

instead of using match function which returns a null if the string doesnt match the provided regex use the test function which returns a true/false and then if you need it you can use the match function.

basically you are performing null.length which is obviously invalid as the match is returning you a null

or you could just perform a null check before you check for the length and just do the regex matching once.

if(linkify!==null && linkify.length!== 0)
{
  //do smthing
}


回答2:

'linkify' is null when there isn't an 'http://' match in the text, so you need to test for that condition:

if(linkify && linkify.length)