0

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);
5
  • 3
    it works fine buddy. Whats the error? Commented Feb 6, 2019 at 12:50
  • Which version of ECMA-Script do you use? Commented Feb 6, 2019 at 12:51
  • Getting this error: Uncaught TypeError: Cannot read property 'map' of null Commented Feb 6, 2019 at 12:55
  • Please, be more specific. Which browser do you use? Which version of Javascript do you use? Without those setup information no one will be able to help you solve your problem. Commented Feb 6, 2019 at 12:57
  • @RojaS are you using any older version of IE browser? As your code works fine in current browser. Check link for more details. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Feb 6, 2019 at 12:59

1 Answer 1

1

String.match return Array<string> | null.

  • If match is found, an array of matched string will be returned.
  • If no match is found, 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'))

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.