eval() 进行字符串替换 | JavaScript

发布于 2024-10-09 11:37:45 字数 794 浏览 0 评论 0原文

使用正则表达式的字符串替换数组是否可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寒尘 2024-10-16 11:37:45

它不是那样工作的。当您调用eval时,您正在eval原始字符串'RGBtoHex($1, $2, $3)'

您需要 将函数传递给 <代码>替换

message.replace(
    /rgb\((\d+), (\d+), (\d+)\)/gi, 
    function(str, r, g, b) { return RGBtoHEX(r, g, b); }
);

It doesn't work like that. When you call eval, you are evaling the raw string 'RGBtoHex($1, $2, $3)'.

You need to pass a function to replace:

message.replace(
    /rgb\((\d+), (\d+), (\d+)\)/gi, 
    function(str, r, g, b) { return RGBtoHEX(r, g, b); }
);
心的位置 2024-10-16 11:37:45

您的 eval 在创建替换数组期间执行。当然,您可以通过简单地传递接受参数而不是替换字符串的函数来在替换时调用代码...例如

"1234".replace(/\d/g,function(x){return parseInt(x)+1})

返回 "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

"1234".replace(/\d/g,function(x){return parseInt(x)+1})

returns "2345" as result

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文