greasemonkey用户脚本在另一个变量中注入变量

时间:2012-03-15 03:00:32

标签: javascript variables split greasemonkey quotes

所以目前我正在尝试为我制作的用户脚本添加一项功能。

目前,用户脚本会将一些文本输入变量。现在还有2个vars,目前用于在第一个var中添加文本到begenning和text的结尾。这是一个代码示例,可以让您更好地了解它目前正在做什么

elmTextarea.value   = opening + elmTextarea.value + closing;

其中elmTextarea是用户脚本得到的字符串,而开放和关闭是我在其开头和结尾放置的内容。

现在,我想要发生的是,如果变量elmTextarea包含任何[quote *] blahblahblah [/ quote],它基本上将排除那些区域(不是明星可能是任何东西,它的格式为

[quote='name' pid='20784507' dateline='1331755619'])

但也可能只是[quote]

所以这是一个快速示例,以便您更好地理解

如果elmTextarea是

blahbla
[quote='name' pid='20784507' dateline='1331755619']
some more text
[/quote]

here is some more

[quote='name' pid='20523454507' dateline='1335435619']
some more text in here
[/quote]

and finally this text

它会变成

opening + blahbla + closing
[quote='name' pid='20784507' dateline='1331755619']
some more text
[/quote]

opening + here is some more + closing

[quote='name' pid='20523454507' dateline='1335435619']
some more text in here
[/quote]

opening + and finally this text + closing

所以我知道这是如何工作的,这是我尝试的实现

var openingquote = closing + "[quote";
var closingquote = "[/quote]" + opening;
elmTextarea.value   = opening + elmTextarea.value + closing;
elmTextarea.value = elmTextarea.value.replace(/[quote/gim, openingquote);
elmTextarea.value = elmTextarea.value.replace(/[\/quote]/gim, closingquote);

但是将这些行添加到我的代码中会使我的整个脚本无效。关于为什么这不起作用以及如何解决它的任何想法。

1 个答案:

答案 0 :(得分:1)

方括号在正则表达式中具有特殊含义。这些也应该被转义:

elmTextarea.value = elmTextarea.value.replace(/\[quote/gim, openingquote);
elmTextarea.value = elmTextarea.value.replace(/\[\/quote]/gim, closingquote);
//                                             ^ Escape [ using \[