1

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.

2 Answers 2

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); }
);
Sign up to request clarification or add additional context in comments.

4 Comments

Ah, thanks for that. I've certainly gave a read on that documentation. Thanks! :) will vote in 3 minutes
I am a bit curious as to your example, where do str, r, g, b com from? I mean say I have this code var templateString = '<div class="slide" style="background-image:url(|@imageURL|); width:|@width|px;" ></div>'; var regex = /\|@([a-zA-z1-9_]*)\|/g; var imageURL = 'someImage.jpg'; var width = 500; var replaceString = templateString.replace(regex, '$1') can I somehow eval $1 to get the imageURL value and width value?
Oh I worked it out=) Still looks like magic but var replaceString = templateString.replace(regex, function(x, y) { console.log(x); console.log(y); var value = eval(y); return value;} ); is exactly what I needed
@Olga: See the documentation: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… The callback takes parameters
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.