undefinedfix
Sign in

Code regular replacement, number calculation

vaiski edited in Sat, 19 Nov 2022

No matter which development tool, regular replacement, replace 20rpx with 10px, divide the number by 2, how to write regular is in the development tool, or write a method

2 Replies
alexfang609
commented on Sat, 19 Nov 2022

This is JS. Editors are similar

// => 将10px即可饥渴18.5px
'将20rpx即可饥渴37rpx'.replace(/(\d+)rpx/g, (g, $1) => {
    return $1 / 2 + 'px'
})
ecisse
commented on Sat, 19 Nov 2022

Ideas: 1. Divide the string into an array according to rpx. 2. The first element of the array is the number. 3. Splice the number / 2 obtained in the second step into PX string and return function topx (STR){

const arr = str.split('rpx');
return Math.round(arr[0] / 2) + 'px';

}

console.log (toPx('20rpx'));