Reputation: 682
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>
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
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