简体   繁体   中英

React Native: <string>.matchAll is not a function

I get a weird error when running my React Native app:

Some sample code:

const { url } = <incoming object>;
const reURL   = <my regex>;

console.debug('url:', url);
console.debug('typeof url:', typeof url);

matches = [...url.matchAll(reURL)];

Log output:

url: <as expected>
typeof url: string

Error message:

TypeError: url.matchAll is not a function. (In 'url.matchAll(reURL)', 'url.matchAll' is undefined)

Everything works fine on iOS, the error only occurs on Android.

Pretty up to date environment, updated all npm packages a couple of days ago.

Does anyone have the slightest idea where to even begin searching for a solution?

I have the same issue. String.matchAll does not work for Android. You should use match instead matchAll .

Example:

const regex = new RegExp(text, 'ig');
const arr = string.match(regex);

You will get an array match regex

You can use string.prototype.matchall to polyfill.

https://www.npmjs.com/package/string.prototype.matchall

import matchAll from 'string.prototype.matchAll'

matchAll.shim()

For us, this issue was solved by conditionally evaluating matchAll:

ourSring.matchAll?.(expr);

Our working theory is that the first time this method is accessed, some native async regex initialization is run, but takes some time to bind the method, resulting in undefined matchAll method. Subsequent evaluations work properly for us.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM