Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  32] [ 2]  / answers: 1 / hits: 33416  / 12 Years ago, tue, april 17, 2012, 12:00:00

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.


More From » jquery

 Answers
16

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
}

[#86202] Sunday, April 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ashli

Total Points: 210
Total Questions: 94
Total Answers: 96

Location: Austria
Member since Sat, Jul 24, 2021
3 Years ago
;