Maxim Yefremov Maxim Yefremov - 3 years ago 116
Javascript Question

Error object to string

I want to use regular expression for error message...

try {
throw new Error("Foo 'bar'");
} catch (err) {
console.log(getInQuotes(err));
}


... where getInQuotes is a function for string:

var getInQuotes = function(str) {
var re;
re = /'([^']+)'/g;
return str.match(re);
};


... but got error:

Object Error: Foo 'bar' has no method 'match'


Although it works for usual string:

console.log(getInQuotes("Hello 'world'"));


result:

[ '\'world\'' ]


Tried to stringify Error object ...

console.log("stringify: " + JSON.stringify(err));


... but it's empty:

stringify: {}

Answer Source

You created an Error object, and that's not a string. But you can simply solve this by calling its toString method, and applying match on the result of that:

function getInQuotes(err) {
  var re;
  re = /'([^']+)'/g;
  return err.toString().match(re);
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download