如何在 React-Native Webview 的注入 JavaScript 道具中使用 RegExp? [英] How to use RegExp in React-Native Webview's injectedJavaScript prop?
问题描述
当我在 React-Native-Webview 的注入 JavaScript 道具中使用正则表达式时,将抛出错误 未终止的正则表达式文字错误
,并且将不遵守正则表达式.
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.
我应该如何在注入的 JavaScript 中使用正则表达式? 如果没有,是否有我可以使用的解决方法?
最小可重现代码如下:
// 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*/`}
/>
- 操作系统:iOS
- 操作系统版本:13.3.1
- 反应原生版本:0.61.2
- react-native-webview 版本:8.1.2
同时检查下面的错误屏幕.
Check the bug screen below as well.
完整的错误信息:
评估injectedJavaScript 时出错:这可能是由于不支持的返回类型.尝试在您注入的 JavaScript 字符串的末尾添加 true.错误域=WKErrorDomain 代码=4 发生 JavaScript 异常" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: 未终止的正则表达式文字 '/', WKJavaScriptExceptionColumnNumber=0, WKJavaScriptExceptionSourceURL=https://github.com/ashi009/node-fast-html-parser, NSLocalizedDescription=发生 JavaScript 异常}
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}
推荐答案
您不是在编写普通的 Javascript - 您正在编写 Javascript 在 webview 中,必须首先评估您的语法.要在 injectedJavaScript
中使用文字反斜杠(例如,对于 \r
),请改为使用两个反斜杠 (\\r
):
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/);`}
我认为
<WebView
source={{ uri: 'https://github.com/ashi009/node-fast-html-parser' }}
injectedJavaScript={`const regE = new RegExp(/\n|\r/);`}
/>
将字符串文字中的 \n
作为代码中的换行符,相当于:
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/);`}
/>
(用 \r
做同样的事情).但是正则表达式文字中不允许换行.
(and the same thing is done with the \r
). But newlines aren't permitted in regular expression literals.
这篇关于如何在 React-Native Webview 的注入 JavaScript 道具中使用 RegExp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!