首页 > 解决方案 > 用正则表达式替换值

问题描述

正则表达式是我永远无法理解的事情之一。我试过使用正则表达式工具,但我做不到。有人可以帮我吗?我正在使用 jquery

如果我有一个 css text-shadow 属性

rgba(0,0,0,0.1) 10px 20px 5px

我的比例为 0.5

我将如何获得每个位置值,将其乘以 0,5 的比率并返回一个新字符串

rgba(0,0,0,0.1) 5px 10px 2.5px 

那么是否可以为具有多个值的文本阴影做到这一点?喜欢

rgba(0,0,0,0.1) 15px 12px 5px, rgba(0,0,0,0.1) 25px 30px 6px, rgba(0,0,0,0.1) 5px 15px 25px

我想您可以将其拆分然后对每个值执行替换?

任何帮助深表感谢。

谢谢

标签: javascriptjquerycssregex

解决方案


假设 text-shadow 的属性的定位是在 order 中'color h-shadow v-shadow blur-radius'。下面的函数应该可以解决这个目的。

function generateScaledValues(x, scale){
    //Assuming the input string is equally separated by ", "
    let result = x.split(", ").map(e=>{
                    let arr = e.split(" ")
                    //.match(/\d+/g) is used to find the number from the string 
                    // example it will return an array ['20'] for '20px'
                    // furthur we need to convert it into number using Number()
                    // which is then multiplied with the scaling factor
                    let hShadow = Number(arr[1].match(/\d+/g)[0])*scale 
                    let vShadow =Number(arr[2].match(/\d+/g)[0])*scale 
                    let blurRadius = Number(arr[3].match(/\d+/g)[0])*scale 
                    return `${arr[0]} ${hShadow}px ${vShadow}px ${blurRadius}px`
                 })
    return result
}

let textShadowProps = "rgba(0,0,0,0.1) 15px 12px 5px, rgba(0,0,0,0.1) 25px 30px 6px, rgba(0,0,0,0.1) 5px 15px 25px"

// The result will be an array of strings for multiple values which we join using the below code
console.log(generateScaledValues(textShadowProps, 0.5).join(", "))


推荐阅读