3

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 ) ?

2 Answers 2

2

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))
)

Sign up to request clarification or add additional context in comments.

2 Comments

it works!! i'm curious now...it only gets the first occurence of rgb/rgba... what if there were more than one?
You can use a global flag g to match multiple occurrences. /rgba?\(.*?\)/g should work.
0

Along with the regex approach, you could also try something like this

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

return "rgb"+str.split('rgb').pop().split(')').shift()+")"; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.