eval() 进行字符串替换 | JavaScript
使用正则表达式的字符串替换数组是否可以使用 eval
来执行函数并返回一个值,我需要通过此方法完成:
var message = $('#message').html();
var searchstring = [
/<span style="color: rgb((.*), (.*), (.*));">(.*)<\/span>/gi,
// other regex
];
var replacestring = [
eval('RGBtoHex($1, $2, $3)'),
// other regex
];
for(i = 0; i < searchstring.length; i++)
{
message = message.replace(searchstring[i], replacestring[i]);
}
$('.message-box').val(message);
我正在尝试将 RGB 转换为十六进制值,因此它应该更改为:rgb(255, 255, 255)
到 #FFFFFF
。但是,当我这样做时,它在 Firebug 中说:$1 is not Defined
,它位于:eval('RGBtoHex($1, $2, $3)'),
。
在使用 .replace()
进行字符串替换时,如何执行 eval()
函数将 rgb 返回为十六进制值?
除了 eval 部分之外,一切都运行良好。
Is it possible that an array of string replacements using regex can use eval
to execute and return a value from a function which I need to be done via this method:
var message = $('#message').html();
var searchstring = [
/<span style="color: rgb((.*), (.*), (.*));">(.*)<\/span>/gi,
// other regex
];
var replacestring = [
eval('RGBtoHex($1, $2, $3)'),
// other regex
];
for(i = 0; i < searchstring.length; i++)
{
message = message.replace(searchstring[i], replacestring[i]);
}
$('.message-box').val(message);
I'm trying to convert RGB to a hexadecimal value so it should change to something like: rgb(255, 255, 255)
to #FFFFFF
. However, when I do this it says in Firebug: $1 is not defined
which is located for this: eval('RGBtoHex($1, $2, $3)'),
.
How will I be able to execute an eval()
function to return rgb to a hexadecimal value while doing string replacements with .replace()
?
Everything works perfectly except the eval part.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不是那样工作的。当您调用
eval
时,您正在eval
原始字符串'RGBtoHex($1, $2, $3)'
。您需要 将函数传递给 <代码>替换:
It doesn't work like that. When you call
eval
, you areeval
ing the raw string'RGBtoHex($1, $2, $3)'
.You need to pass a function to
replace
:您的 eval 在创建替换数组期间执行。当然,您可以通过简单地传递接受参数而不是替换字符串的函数来在替换时调用代码...例如
返回
"2345"
作为结果Your eval is executed during the creation of the replacement array. Sure you can call code at replacement time by simply passing a function accepting a parameter instead of a substitute string... for example
returns
"2345"
as result