Replace statement not working for different html tag color retrieving from service

Viewed 83

I have 2 statement coming in string as below

"<font color='#F7D122'>".replace(/color='/g, "style='color:")

will return

<font style='color:#F7D122'>

but how can I replace below one ?

"<font color=#F7D122>".replace(/color='/g, "style='color:")

will return

 <font color=#F7D122>

but Instead I want return as

<font style='color:#F7D122'>

In second replace statement you can find that string does not contain single quotes

2 Answers

Using a regex replacement:

// first version, with the hex color in quotes
var input = "<font color='#F7D122'>";
var output = input.replace(/<font\s+([^=]+)=(?:'(\S+)'|(\S+))\s*>/, "<font style='$1:$2$3'>");
console.log(input + " => " + output);

// second version, hex color without quotes
var input = "<font color=#F7D122>";
var output = input.replace(/<font\s+([^=]+)=(?:'(\S+)'|(\S+))\s*>/, "<font style='$1:$2$3'>");
console.log(input + " => " + output);

This is a more generic version of what you were trying to do, and covers any <font> tag with a single property inside it having the key=value format.

The regex trick used here is that we match either color='#F7D122', with single quotes, or color=#F7D122, without quotes, in separate capture groups ($2 and $3). Then, we replace with both $2$3. Only one will have any content, and it will be the hex color without single quotes.

Use a regex to get the HEX color code, then use $1(first group) to insert that in the replace statement.

const test1 = "<font color=#F7D122>";
const test2 = '<font color="#F7D122">';
console.log(test1.replace(/color=(?:"|'?)(#[0-9A-F]{6})(?:"|'?)/g, "style='color: $1'"));
console.log(test2.replace(/color=(?:"|'?)(#[0-9A-F]{6})(?:"|'?)/g, "style='color: $1'"));

Related