3

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: {}

4 Answers 4

5

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);
};
Sign up to request clarification or add additional context in comments.

Comments

1

Just try this http://jsfiddle.net/B6gMS/1/

getInQuotes(err.message)

Comments

1

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.

  1. This uses template literals in RegExp Function.
  2. Annotator is configurable
  3. change the method name getInQuotes to getAnnotatedStrings which is meaningful.
  4. method return always array in order to keep it predictable and avoid other errors.
  5. 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

Comments

0

err is not a string it's an Error object, so it has no .match() function . You Should call the function using Error object's toString() method, just this way:

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

Comments

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.