简体   繁体   中英

Replace color strings in HTML string within tags

I have a string that contains HTML. Now I want to replace all occurrences of colors within tags with something. How do I do this?

const workInProgressRegex = /<[\w]+[^>]*>.*?(#(?:[0-9a-fA-F]{3}){1,2})<\/[\w]+>/gim;

const exampleString1 = `<div><span class="foo" style="background-color: #ffffff;">#222222 foo #111111 abc #000000</span></div>`;

const exampleString2 = `<div><span class="foo" style="background-color: #ffffff;">"'#222222 foo #111111 abc #000000</span></div>`;

const result1 = exampleString1.replaceAll(workInProgressRegex, "bar");
// should be `<div><span class="foo" style="background-color: #ffffff;">bar foo bar abc bar</span></div>`

const result2 = exampleString1.replaceAll(workInProgressRegex, "bar");
// should be `<div><span class="foo" style="background-color: #ffffff;">"'bar foo bar abc bar</span></div>`

Additional info: I want to replace all text occurrences of any hex colors inside the HTML tags. The examples I gave are just examples and not exhaustive.

Although I am not looking for something unbreakable, it should be robust. That means, the hex codes can be at any position inside the innerHTML, they do not have to be at the end or beginning. There also can be an arbitrary amount of those hex codes in the tag.

I think you are looking for this regex (#[0-9|af]{6}) which should select all of your hex color codes.

https://regex101.com/r/Xvct56/2/

The problem is that you can't simply replace all occurences of #xxxxxx because that would also remove style="background-color: #ffffff;" from your string which is what you want to keep.

What you can do however is chaining two replace functions where the first one looks for the pattern #xxxxxx[empty space] and the second one for #xxxxxx< (because of the last occurence #000000</span> which would be replaced by bar /span> otherwise).

 const exampleString2 = `<div><span class="foo" style="background-color: #ffffff;">"'#222222 foo #111111 abc #000000</span></div>`; var res = exampleString2.replace(new RegExp(/(#[0-9|af]{6} )/, 'g'), 'bar ').replace(new RegExp(/(#[0-9|af]{6}<)/, 'g'), 'bar<'); console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM