Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

js regex replace all RGB colors

I am trying to use regex to apply algorithm to all rgb in the string.

let st = `
:root {
  --bg-body: rgb(14, 14, 34);
  --bg-wrapper: rgb(14,14,35);
  --color-left-hover: rgb(66,85, 212);
  --bg-header: radial-gradient(circle, rgb(20, 24, 52) 0%, rgb(19, 22, 47) 100%); 
}
`

st.replaceAll(/rgb\(.*\)/g, rgb=>{
    console.log(rgb);
});
[Log] rgb(14, 14, 34) 
[Log] rgb(14,14,35) 
[Log] rgb(66,85, 212) 
[Log] rgb(20, 24, 52) 0%, rgb(19, 22, 47) 100%)

it seems the regex does not work for the last one. refers to Javascript Regular Expression for rgb values, I tried some of the expressions, however I usually got:

TypeError: String.prototype.replaceAll argument must not be a non-global regular expression

or the regex is not returning valid mapping result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I will be very grateful for your help.

>Solution :

I would use match here:

let st = `
:root {
  --bg-body: rgb(14, 14, 34);
  --bg-wrapper: rgb(14,14,35);
  --color-left-hover: rgb(66,85, 212);
  --bg-header: radial-gradient(circle, rgb(20, 24, 52) 0%, rgb(19, 22, 47) 100%); 
}
`

var matches = st.match(/rgb\(\d+,\s*\d+,\s*\d+\)/g);
console.log(matches);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading