PDA

View Full Version : Regular Expression help please.



Krupski
01-21-2011, 04:52 PM
Hi all, I have this line (part of a larger function that converts a few common BBCodes into HTML) and I don't know how to do one thing. First, here's the line:



str.replace(/\[color=(.*?)\](.*?)\[\/color\]/gi,'<span style="color:$1;">$2</span>');
It works fine if I do this (I'll mis-spell "color" to prevent messing up the board):

THIS works fine.....
Red Text

But of course, if I do this:
Red Text

It doesn't work.

What I need to do is take the $1 variable, AFTER it's captured, but BEFORE it's used, and strip out any quote marks I find. I may want to also strip out, then add the hash sign (#) also, then put it back so it works with or without the #.

While I'm at it, I'll also probably detect color as a hex string vs. a keyword (so that both "#ff0000" and "red" work) and probably also support the rgb() method.

But first I need to know how to access and modify $1 BEFORE it's used. I'm hoping that I don't need to use two lines (or two separate .replace() calls).

Thanks!

-- Roger

Old Pedant
01-21-2011, 06:36 PM
str.replace(/\[color=[\"\']?(.*?)[\"\']?\](.*?)\[\/color\]/gi,'<span style="color:$1;">$2</span>');

???

Logic Ali
01-21-2011, 06:51 PM
For translating the value you could pass a function as a parameter. Read. (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter)

Something like:

str.replace(/\[color=(.*?)\](.*?)\[\/color\]/gi, function(a, b, c)
{
/* Process b here */

return '<span style="color:' + b + '">' + c + '</span>';
});

Krupski
01-21-2011, 10:35 PM
str.replace(/\[color=[\"\']?(.*?)[\"\']?\](.*?)\[\/color\]/gi,'<span style="color:$1;">$2</span>');

???

Why the "???"?

Krupski
01-21-2011, 10:36 PM
For translating the value you could pass a function as a parameter. Read. (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter)


That LINK is a goldmine! Thanks!

-- Roger