最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

replace - eval() on string replacement | JavaScript - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share asked Dec 30, 2010 at 21:11 MacMacMacMac 35.4k55 gold badges153 silver badges224 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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)

  1. 暂无评论