开发者

eval() on string replacement | JavaScript

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.


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); }
);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜