user15322469
user15322469

Reputation: 909

Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method

i'm using react native with regex

if i use my code

this error occured

Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.

I want to put an empty value like ' ' in the match if any character other than a number and decimal point is included in my regular expression. If you put "123abc" in the value variable, match returns "123", but if you put "acv" in the value constant, the above error occurs. In this case, how can I put an empty string into the match without generating an error?

 const regex = /\d+(\.\d{1,2})?/;

const value = "abd"
const [match] = regex.exec(value);

Upvotes: 1

Views: 3751

Answers (1)

Alan Omar
Alan Omar

Reputation: 4217

you can use || operator. in case exec return null it will default to empty string ''.

function getStrings(value) {
  const regex = /\d+(\.\d{1,2})?/;
  const [match] = [regex.exec(value) || ''];
  if(Array.isArray(match))
    return match[0]
  return match
}

console.log(getStrings("abd"))
console.log(getStrings("123abd"))

Upvotes: 1

Related Questions