"非法字符“;Watir execute_script时出错

"illegal character" error when Watir execute_script

本文关键字:script execute 出错 quot 非法 字符 Watir      更新时间:2023-09-26

我通过用户界面中的文本区域获取JavaScript代码,然后在我的应用程序中执行代码,如下所示:

用户输入:

text = 'I am fine!!! ';
return text.replace(/(.+)'s+$/g, '$1’);

然而,在rails中,转义符被添加到文本区域中的用户输入中:

"text = 'hello how are you? ';''d'r'nreturn text.replace(/(.+)''s+$/g, '$1’);"

因此execute_script语句给出了一个"非法字符"错误。

browser.execute_script("text = 'hello how are you? ';''d'r'nreturn text.replace(/(.+)''s+$/g, '$1’);")

如何在不使用regex的情况下去掉转义符,以便execute_script运行良好?

看看这个:

browser.execute_script("text = 'hello how are you? '; return text.replace(/(.+)''s+$/g, '$1');")

但是!你到底为什么需要它

这是一个非常奇怪的案例,我在Dave的评论中加了+1。做一些javascript魔术并不是典型的用户操作。试着重新想想你在做什么。

您是否考虑过尝试String#gsub!为了这个?以下是我可能会如何处理它:

test = "''d'r'nreturn text.replace(/(.+)''s+$/g, '$1’);"
=> "''d'r'nreturn text.replace(/(.+)''s+$/g, '$1’)"
test.gsub!(/['d'n'r''d]/, '')
=> "return text.replace(/(.+)s+$/"

如果你不想覆盖它,你也可以使用String#gsub,返回一个修改过的副本

test.gsub(/['d'n'r''d]/, '')
=> "return text.replace(/(.+)s+$/"

很明显,您可以自定义正则表达式来自定义您的需要。还要小心使用智能引号,如$1的结束引号,因为' 不同