s.dragos
s.dragos

Reputation: 682

"cannot read property 'length' of null" of RegEx result

I don`t understand why I get an error after I try to execute this simple JS code:

<!DOCTYPE html>
<html>
<script>
    var str = "x*1/2";
    var patt1 = /( * | \/)/g;
    var result = str.match(patt1);
    document.write(result.length);
</script>
</html>
I have tried typeof to see the type of my variables: str=string; patt1=object; result=object; but I still have no clue whats the problem.

Upvotes: 1

Views: 1111

Answers (1)

Christos
Christos

Reputation: 53958

I don`t understand why I get an error after I try to execute this simple JS code

This is happening, because your pattern cannot be matched for the provided input "x*1/2". So match returns null. Consider the following snippet, where we use a meaningless pattern, which however can be matched for this input.

var str = "x*1/2";
var patt1 = /([*]?\/)/g;
var result = str.match(patt1);
console.log(result.length);

Upvotes: 2

Related Questions