Reputation: 29
I am getting this error if i use map in my script. How to resolve this error?
I am getting this error: Uncaught TypeError: Cannot read property 'map' of null
Js Script:
var stringval="global $1200";
var getVal=stringval.match(/\d+/g).map(Number);
Upvotes: 0
Views: 47
Reputation: 24915
String.match return Array<string> | null
.
null
will be rendered.So in you case, if the string does not have any number, it will return null
causing the script to break.
Sample:
function getNumber(stringval) {
return stringval.match(/\d+/g).map(Number);
}
var stringval = "global $1200";
console.log(getNumber(stringval))
console.log(getNumber('Hello World'))
A simple way to solve this is to add a check for existence of match:
function getNumber(stringval) {
// You can set any value based on your requirement
var defaultValue = undefined;
var matches = stringval.match(/\d+/g)
return matches !== null ? matches.map(Number) : defaultValue;
}
var stringval = "global $1200";
console.log(getNumber(stringval))
console.log(getNumber('Hello World'))
Upvotes: 1