18

I recently stumbled on this issue that, though ran well on iOS, could not run on Android, even though I use the same code base and run them in parallel.

Error log on react native 0.64.4

Note that (number + '') always returns a string, and this code runs on iOS.

Trying the regex with the global flag "g":

string.replace(/searchString/g, replaceString)

like some suggested StackOverFlow answers does not work either.

Can you guys guess the reasons and provide solutions?

Hung Vu
  • 360
  • 3
  • 11

3 Answers3

21

Alternative way to do this with the split and join functions.

string.split("searchString").join("replaceString");
Shoaib Khan
  • 1,020
  • 1
  • 5
  • 18
4

replace method works perfectly in the latest React Native version. Please note you need to use string literals (`) instead of quotes (") for string variables.

string.replace(`/${searchString}/g`, replaceString);

Tested on the following React Native version:

react-native-cli: 2.0.1
react-native: 0.64.3
1

TL;DR

  1. Check android/app/build.gradle
    • Search your project for: enableHermes
  2. Change to: true
  3. Clean and Rebuild project

My default:

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
]

Changed to:

project.ext.react = [
    enableHermes: true,  // clean and rebuild if changing
]

I am also facing this issue. It works fine on iOS but with Android, it throws an error.

As suggested by the first comment to OP question, @Krismu, I check if Hermes is enabled. Hermes is a Javascript engine that is bundled with React-native to ensure compatibility and efficiency.

React-native documentation says that is enabled by default and you can opt out.

https://reactnative.dev/docs/hermes#switching-back-to-javascriptcore

However, my android/app/build.gradle file was set to false by default, making my android app not use Hermes.

This solved the problem for me. No need to polyfill, use just 'replace()' or change any code for that matter...

Verison info:

  • "react": "18.0.0",
  • "react-native": "0.69.7",
  • I find it odd that this would exist within Hermes, and not JS Core. This function is native to JS, and should be so regardless of the platform. – Hung Vu Dec 13 '22 at 04:15
  • 1
    JS is standardized in the standard called ECMAScript. `replaceAll` was only very recently introduced into the standard (in the 2021 edition), so not all JS engines support it yet. – user3670473 Feb 09 '23 at 20:28