Regex for value substitution

I've always struggled with understanding regex. Even after trying various tools, I still couldn't grasp it. Can someone please provide me with assistance? I'm working with jquery.

For example, if I have a css text-shadow property like

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

and a scale ratio of 0.5, how can I calculate each position value by multiplying it with the ratio of 0.5 and return a new string as follows:

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

Furthermore, is it feasible to apply this calculation to text-shadows with multiple values, such as:

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

I assume one would need to separate them and then replace each value individually?

Any help on this matter would be greatly appreciated.

Thank you.

Answer №1

Utilize regular expressions to extract the px values and then apply a replacement function to multiply those values

str = "rgba(0,0,0,0.1) 10px 20px 5px"
newstr = str.replace(/(-?\d+\.?\d?)(?=px)/g,o => o*0.5)
console.log(newstr)

Answer №2

When it comes to determining the arrangement of text-shadow properties in the sequence

'color h-shadow  v-shadow blur-radius'
, you can rely on the subsequent function to achieve this goal.

function adjustValues(x, scale){
    //Considering that the input string is separated by ", "
    let result = x.split(", ").map(e=>{
                    let arr = e.split(" ")
                    //.match(/\d+/g) detects numbers from the string 
                    // for instance, it produces an array ['20'] for '20px'
                    // then these are converted into numbers using Number()
                    // and finally multiplied by the scaling factor
                    let horizontalShadow = Number(arr[1].match(/\d+/g)[0])*scale 
                    let verticalShadow = Number(arr[2].match(/\d+/g)[0])*scale 
                    let blurRadius = Number(arr[3].match(/\d+/g)[0])*scale 
                    return `${arr[0]} ${horizontalShadow}px ${verticalShadow}px ${blurRadius}px`
                 })
    return result
}

let shadowProperties = "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 outcome will be an array of strings for various values which are combined using the following code
console.log(adjustValues(shadowProperties, 0.5).join(", "))

Answer №3

If you want to convert the pixel values into half by using a simple JavaScript code, follow these steps:

let pixels = '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';

let splittedPixels = pixels.split(', ');
console.log(splittedPixels);

let halvedArr = splittedPixels.map(item => item.match(/\d+(?=px)/g).map(num => parseInt(num * 0.5))).flat(1);
console.log(halvedArr);

let finalResult = [];

for(let i=0; i<halvedArr.length; i+=3){
    finalResult.push('rgba(0,0,0,0.1) ');
    finalResult.push(halvedArr[i] + 'px ' + halvedArr[i+1] + 'px ' + halvedArr[i+2] + 'px, ');
}

console.log(finalResult);
console.log(finalResul.join(''))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic loading of dependent dropdowns for ActiveAdmin based on the selection made in the first dropdown

As a newcomer to the realm of Ruby on Rails and Active Admin, I find myself tasked with creating two dropdown lists: one for location and another for game. The relationship between location and game is crucial here. Upon selecting a location from the drop ...

Creating a mockup for a website design project in my class, utilizing HTML and CSS. Encountering issues with the CSS not displaying correctly, unsure of the root cause of the problem

Check out this wireframe design I created: https://i.stack.imgur.com/Ro3dl.png I'm working on translating this into HTML and CSS so that I can further develop it. The HTML Code: <!doctype html> <html> <head> <title> Trinit ...

Using regex with multiple negative lookbehinds allows for more sophisticated pattern matching

I have come across some similar questions regarding my issue, but unfortunately I have not been able to make any of the solutions work for me. What I am seeking is a regex pattern with a capturing group that identifies every 'WhatEverDataSet', w ...

Is there a way to retrieve the global variable within a local scope?

I am facing an issue with accessing the global req_no and request_id variables within sql.query blocks. Due to this, the second query is sending empty values for req_no and request_id. My goal is to retrieve the request_id, generate the req_no, and then u ...

What is the process for implementing an image as the background instead of a color for each column in a Google chart?

I'm currently working with Google Chart and I have set up a column chart. However, I am looking to display a background image instead of a background color in each column. Is this achievable with Google Chart? If so, how can I accomplish this? If anyo ...

The scroll feature in JavaScript is malfunctioning

After countless hours of troubleshooting, I still can't figure out why the code snippet below is not working properly on my website at : <script> $(window).scroll(function () { if ($(window).scrollTop() > 400) { ...

Characteristics within the primary template element of a directive

I'm having an issue with the following directive code: .directive('myDirective', function () { restrict: 'E', replace: true, transclude: true, scope: { label: '@', ngModel: '=', ...

Having difficulty running assessments on the connected components

I have encountered an issue while using the MERN stack and Redux. Specifically, I am facing errors when trying to write test cases for certain components. The error message I receive states: "Could not find "store" in the context of "C ...

How to alter the color of a Twitter bootstrap progress bar

Recently, I have been exploring Twitter bootstrap and encountered an issue while trying to customize the progress bar. Despite my efforts, I am unable to display the progress bar on the screen. Here is the code snippet that I have been working with. Despi ...

Using VueJS to Create a Range of Years from 1900 to Present Year

I'm currently developing a registration form using VueJS, wherein users need to input their date of birth. My challenge is in generating a list of years starting from 1900 up to the current year within a <select> element. Any suggestions on how ...

What is preventing the execution of the bower update command in the Package Manager Console?

After encountering issues with upgrading the jQuery version in an existing project, I attempted to use Package Console Manager (PMC) to run bower update jquery --force-latest as well as bower update jquery. Unfortunately, both attempts were unsuccessful an ...

Error in Babel-Loader when executing npm run build

Not being a webpack expert, I decided to upgrade from V3 to V4. After fixing the depreciation errors in my webpack config, I hit a roadblock with a syntax error from babel-loader: Module build failed (from ./node_modules/babel-loader/lib/index.js): ...

What is the reason for encountering the error message "Property 'floatThead' does not exist on type 'JQuery<any>' when trying to use floatThead in Angular/TypeScript?

For my project, I am incorporating the third-party jQuery library called https://github.com/mkoryak/floatThead. To work with Bootstrap and jQuery, I have installed them using NPM through the command line. Additionally, I have used NPM to install floatThea ...

Attempting to modify the animation speed of a fadeOut queue in jQuery from "slow" to the digit "3000" is proving unsuccessful

Here is a snippet of code that I have successfully used for animation and fadeOut simultaneously: $('#vote').fadeOut({queue: false, duration: 'slow'}); $('#vote').animate({ top: "-10px", left: "25px" }, 'slow'); Ho ...

Initiate communication with the server by sending a callback through ajax

Whenever I click the "Add Role" button, I want to make a callback to the server in order to receive a partial view for my modal. However, nothing seems to happen when I click the button. Here is the JavaScript code snippet: $(".addRole").on("click", func ...

What is the best way to determine if an array of objects is present in the state of a React

Currently, I am in the process of developing a dynamic form using React JS. One aspect of my form involves an input field with a limit of 10 characters. To enhance the cleanliness of my code, I have constructed an object and utilized mapping to streamline ...

Ensure HTML5 video fills window completely without any overflow

I'm currently developing a new open-source alternative to Plex and I am facing some challenges with the in-browser video player. My goal is to have the video player maximize its size within the window during playback, similar to what Chrome and Netfli ...

Center alignment is not possible for the Div element

Problem Every time I attempt to implement the following code (outlined below), the div only appears centered when using width: 100px;. <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; margin-left: auto; mar ...

The background images aren't tiling properly on mobile safari

Having a peculiar issue with Mobile Safari. Background images on some divs are not reaching all the way across the page, stopping just before halfway. Interestingly, they display properly in Safari on both PC and Mac. You can view the site online at: www. ...

The animated sticky header lacks smooth animation while scrolling upwards

This dynamic menu transitions the logo to the left and the navigation to the right as you scroll down. The animation is smooth when scrolling down, but slightly jerky when scrolling up, especially with the navigation. The animation uses CSS3: transition: ...