我想使用正则表达式来显示错误消息......
try {
throw new Error("Foo 'bar'");
} catch (err) {
console.log(getInQuotes(err));
}
Run Code Online (Sandbox Code Playgroud)
...其中 getInQuotes 是字符串函数:
var getInQuotes = function(str) {
var re;
re = /'([^']+)'/g;
return str.match(re);
};
Run Code Online (Sandbox Code Playgroud)
...但出现错误:
Object Error: Foo 'bar' has no method 'match'
Run Code Online (Sandbox Code Playgroud)
虽然它适用于普通字符串:
console.log(getInQuotes("Hello 'world'"));
Run Code Online (Sandbox Code Playgroud)
结果:
[ '\'world\'' ]
Run Code Online (Sandbox Code Playgroud)
尝试将错误对象字符串化...
console.log("stringify: " + JSON.stringify(err));
Run Code Online (Sandbox Code Playgroud)
...但它是空的:
stringify: {}
Run Code Online (Sandbox Code Playgroud)
您创建了一个 Error 对象,但它不是一个字符串。但是您可以通过调用其toString方法并对结果应用匹配来简单地解决此问题:
function getInQuotes(err) {
var re;
re = /'([^']+)'/g;
return err.toString().match(re);
};
Run Code Online (Sandbox Code Playgroud)