无法在javascript for循环中读取null的属性'length' [英] Cannot read property 'length' of null in javascript for loop
问题描述
我正在尝试制作像Stack Overflow这样的降价编辑器。
I'm trying to make a markdown editor like Stack Overflow has.
如果我实际上没有输入星号,我会在标题中列出此错误一个http://包含短语到textarea。如果我只输入包含短语的星号,则错误引用此行: if(linkify.length!== 0)
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)
这是 jsfiddle ,向您展示我的意思。
Here's a jsfiddle to show you what I mean.
这是我的HTML:
<textarea></textarea>
<div></div><button type="button">Markdownify</button>
这是我的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.
推荐答案
而不是使用匹配
函数,如果字符串与提供的正则表达式不匹配则返回null使用测试
返回true / false的函数,如果需要,可以使用 match
函数。
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.
基本上你正在执行 null.length
这显然无效,因为匹配
返回null
basically you are performing null.length
which is obviously invalid as the match
is returning you a null
或者您可以在检查长度之前执行 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
}
这篇关于无法在javascript for循环中读取null的属性'length'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!