简体   繁体   中英

replace linear-gradient percentage by using regex

This is my first time to use regex, I would like to replace the second rgb percentage from 10% to 30%. Such as rgb(251, 188, 5) 10% to rgb(251, 188, 5) 30%

I've tried to search through online, but couldn't get what I really need. below is my testing code, I am only able to get the rgb(251, 188, 5) , how can I include the 10% for me to replace it? or direct access to the 10% and replace it to 30%?

before change:

linear-gradient(rgb(251, 188, 5), rgb(251, 188, 5) 10%, rgb(223, 223, 223) 0%, rgb(223, 223, 223) 100%)

expected result:

linear-gradient(rgb(251, 188, 5), rgb(251, 188, 5) 30%, rgb(223, 223, 223) 0%, rgb(223, 223, 223) 100%)

 const r = "linear-gradient(rgb(251, 188, 5), rgb(251, 188, 5) 10%, rgb(223, 223, 223) 0%, rgb(223, 223, 223) 100%)".replace(/(?<=rgb.*?)rgb\(.*?\)/, '30%') console.log(r)

You can use

.replace(/^(.*?\brgb.*?\brgb\([^()]*\)\s*)\d+(?:\.\d+)?%/, '$130%')

See the regex demo .

Details

  • ^ - start of string
  • (.*?\brgb.*?\brgb\([^()]*\)\s*) - Group 1 ( $1 ):
    • .*? - any zero or more chars other than line break chars as few as possible
    • \brgb.*? - a word boundary and rgb and any zero or more chars other than line break chars as few as possible
    • \brgb\( - rgb whole word and ( char
    • [^()]* - zero or more chars other than ( and )
    • \) - a ) char
    • \s* - zero or more whitespaces
  • \d+(?:\.\d+)? - one or more digits, and then an optional sequence of a . and one or more digits (not necessary for the current example, but good to have if you have numbers with fractional parts)
  • % - (actually, it is here to just assure we have a percentage value, it might not be necessary) - a % char.

JavaScript demo:

 console.log( "linear-gradient(rgb(251, 188, 5), rgb(251, 188, 5) 10%, rgb(223, 223, 223) 0%, rgb(223, 223, 223) 100%)".replace(/^(.*?\brgb.*?\brgb\([^()]*\)\s*)\d+(?:\.\d+)?%/, '$130%') )

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