Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx JS extract string matching criterias from another string

I have this type of strings:

url('img.png') rgba(123, 111, 23, 0.96) none repeat scroll 0% 0% / auto padding-box padding-box

url('img.png') rgb(123, 111, 23) none repeat scroll 0% 0% / auto padding-box padding-box

note the rgb/rgba difference

and I need to extract only rgba(123, 111, 23, 0.96) or rgb(123, 111, 23)

essentially, how to I select strings that starts with rgb and ends with a parenthesis ) ?

like image 578
Francesco Avatar asked Nov 17 '25 06:11

Francesco


1 Answers

You can use /rgba?\(.*?\)/ with String.match method; rgba? matches rgb or rgba, \(.*?\) matches the first pair of parenthesis after, which assumes you have no nested parenthesis:

var samples = ["url('img.png') rgba(123, 111, 23, 0.96) none repeat scroll 0% 0% / auto padding-box padding-box",
"url('img.png') rgb(123, 111, 23) none repeat scroll 0% 0% / auto padding-box padding-box"]

console.log(
  samples.map(s => s.match(/rgba?\(.*?\)/))
)

// if have more than one matches in the strings

console.log(
  samples.map(s => s.match(/rgba?\(.*?\)/g))
)
like image 139
Psidom Avatar answered Nov 18 '25 20:11

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!