Basically, here we are trying to get the annotated string. if we go with Regular Expression then we need a right case if there is a real need for this.
if not, below string replace would be easier solution.
// Arrow Function read given string and strip quoted values.
// Basic example
const getInQuotes = (str) => str.replace( /^[^']*'|'.*/g, '' );
In order to keep it more generic. below function helps to keep this annotator (') can be configurable. below code is in latest ES2021 code.
- This uses template literals in RegExp Function.
- Annotator is configurable
- change the method name
getInQuotes to getAnnotatedStrings which is meaningful.
- method return always array in order to keep it predictable and avoid other errors.
- Its good not to pass entire object since its requires only the error message.
function getAnnotatedStrings(errorMessage, annotator = "'") {
if (!annotator || !errorMessage) return []
const regex = new RegExp(`${annotator}([^']+)${annotator}`, 'g')
return errorMessage.toString().match(regex);
}
Actual in ES2021 Code.
try {
throw new Error("Foo 'bar'");
} catch (e) {
console.log(getAnnotatedStrings(e?.message)); // outputs - bar
}
Refer:
Error Object Intro
Regex Functions and Basics
Template Literals