How to use RegExp in React-Native Webview's injectedJavaScript prop?

眉间皱痕 提交于 2020-04-18 05:42:32

问题


When I use regexp in React-Native-Webview's injectedJavaScript prop, an error Unterminated regular expression literal error will be thrown and the regexp will not be honored.

How should I use regexp in injectedJavaScript? If not, is there a workaround I can use?

Minimal reproducible code is below:

// this won't work
<WebView
  source={{ uri: 'https://github.com/ashi009/node-fast-html-parser' }}
  injectedJavaScript={`const regE = /\n|\r/`}
/>

// this won't work as well
<WebView
  source={{ uri: 'https://github.com/ashi009/node-fast-html-parser' }}
  injectedJavaScript={`const regE = new RegExp(/\n|\r/);`}
/>

// this will work
<WebView
  source={{ uri: 'https://github.com/ashi009/node-fast-html-parser' }}
  injectedJavaScript={`const regE = /A*B*C*/`}
/>
  • OS: iOS
  • OS version: 13.3.1
  • react-native version: 0.61.2
  • react-native-webview version: 8.1.2

Check the bug screen below as well.

Full Error Message:

Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string. Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: Unterminated regular expression literal '/', WKJavaScriptExceptionColumnNumber=0, WKJavaScriptExceptionSourceURL=https://github.com/ashi009/node-fast-html-parser, NSLocalizedDescription=A JavaScript exception occurred}


回答1:


You're not writing plain Javascript - you're writing Javascript inside the webview, through which your syntax has to be evaluated first. To use a literal backslash in injectedJavaScript (eg, for \r), put two backslashes instead (\\r):

injectedJavaScript={`const regE = new RegExp(/\\n|\\r/);`}

I think that

<WebView
  source={{ uri: 'https://github.com/ashi009/node-fast-html-parser' }}
  injectedJavaScript={`const regE = new RegExp(/\n|\r/);`}
/>

takes the \n in the string literal to be a newline in the code, and equivalent to:

<WebView
  source={{ uri: 'https://github.com/ashi009/node-fast-html-parser' }}
  injectedJavaScript={`const regE = new RegExp(/
|\r/);`}
/>

(and the same thing is done with the \r). But newlines aren't permitted in regular expression literals.



来源:https://stackoverflow.com/questions/60910417/how-to-use-regexp-in-react-native-webviews-injectedjavascript-prop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!