Home > OS >  Regex CSS Style Attribute replacements
Regex CSS Style Attribute replacements

Time:11-26

I want to selectively replace an attribute value within a CSS Style string...

The string:

"font-size:13pt;font-weight:600;line-height:140%;padding-top:10px;font-family:'Open Sans', 'Droid Sans', Arial, sans-serif;color:#7f1a52;padding-bottom:5px;vertical-align:middle;background-color:; text-align:center;align:center;"

I want to selectively replace the "center" in text-align and align, but NOT the middle in vertical-align.

So far I have

string.replace(/(?<=align:)(.*?)(?=;)/g,"right")

but that will also replace the middle in vertical align.

How can I exclude vertical-align:middle from being selected within this string??

CodePudding user response:

Why would you do it with regex?

just take the element and use Element.style.property

So to override text-align, you can just use Element.style.textAlign = 'other value'

CodePudding user response:

You can rule out only vertical- and capture align: in group 1. Then match the part until the semicolon that you want to replace.

In the replacement use group 1, followed by right

\b(?<!vertical-)(align:)[^;] 

Regex demo

const regex = /\b(?<!vertical-)(align:)[^;] /g;
const str = `font-size:13pt;font-weight:600;line-height:140%;padding-top:10px;font-family:'Open Sans', 'Droid Sans', Arial, sans-serif;color:#7f1a52;padding-bottom:5px;vertical-align:middle;background-color:; text-align:center;align:center;`;
const result = str.replace(regex, `$1right`);

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related