Ways to change a portion of a string with javascript regular expressions

Seeking guidance on isolating the width attribute in CSS:

oldStyle = "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"

Considering this code snippet:

oldStyle.replace(new RegExp("width:[0-9]+%;.*$", "g"), "width:25%;")

However, the output yields only:

"width:25%;"

The desired outcome should be:

"width:25%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"

How can I modify solely the width component of the CSS while preserving the remaining styles?

Answer №1

There's no need to rely on regular expressions for this task as there are simpler alternatives available.

Basic manipulation of strings

The approach involves parsing and manipulating the string, keeping in mind its simple structure: segments separated by semicolons, where each segment consists of a key and value separated by a colon:

function adjustWidth(style, newValue) {
  const segments = style
    .slice(0, -1) //remove the last `;`
    .split(';');
    
  const nonWidthSegments = segments.filter(segment => !segment.startsWith("width"));
  
  return nonWidthSegments
    .concat(`width: ${newValue}`)
    .join(';')
    .concat(';'); //add back the last `;`
}

console.log(adjustWidth(
  "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;",  
  "45px"
));

console.log(adjustWidth(
  "margin: auto;",  
  "45px"
));

console.log(adjustWidth(
  "",  
  "45px"
));

This method can be expanded to modify any property. To ensure an exact match (e.g., avoiding mismatching properties like "border-width-radius" instead of "border-width"), the .startsWith() method is modified for accuracy:

function adjustStyle(style, property, newValue) {
  const segments = style
    .slice(0, -1) //remove the last `;`
    .split(';');
    
  const otherSegments = segments.filter(segment => segment.split(":")[0].trim() !== property);
  // ensuring exact property name           --->      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  
  return otherSegments
    .concat(`${property}: ${newValue}`)
    .join(';')
    .concat(';'); //adding the last `;`
}

console.log(changeStyle(
  "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;",  
  "width",
  "45px"
));

console.log(changeStyle(
  "margin: auto;",  
  "width",
  "45px"
));

console.log(changeStyle(
  "",  
  "width",
  "45px"
));

console.log(changeStyle(
  "padding-right: 15px;border-width-radius: 10px;",  
  "border-width",
  "4px"
));

console.log(changeStyle(
  "padding-right: 15px;border-width-radius: 10px;border-width: 10px;",  
  "border-width",
  "4px"
));

Manipulating the DOM

Creating an in-memory DOM node allows direct manipulation of styles using the DOM API, eliminating issues related to handling strings:

function adjustWidth(style, newValue) {
  const el = document.createElement("div");
  
  el.setAttribute("style", style);
  
  el.style.width = newValue;
  
  return el.getAttribute("style");
}

console.log(changeWidth(
  "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;",  
  "45px"
));

console.log(changeWidth(
  "margin: auto;",  
  "45px"
));

console.log(changeWidth(
  "",  
  "45px"
));

This approach can easily be adapted without needing to handle additional cases:

function adjustStyle(style, property, newValue) {
  const el = document.createElement("div");
  
  el.setAttribute("style", style);
  
  el.style[property] = newValue;
  
  return el.getAttribute("style");
}

console.log(changeStyle(
  "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;",  
  "width",
  "45px"
));

console.log(changeStyle(
  "margin: auto;",  
  "width",
  "45px"
));

console.log(changeStyle(
  "",  
  "width",
  "45px"
));

console.log(changeStyle(
  "padding-right: 15px;border-width-radius: 10px;",  
  "border-width",
  "4px"
));

console.log(changeStyle(
  "padding-right: 15px;border-width-radius: 10px;border-width: 10px;",  
  "border-width",
  "4px"
));

Answer №2

To achieve the desired outcome, you can utilize the following regular expression. This regex will substitute any width specified in units such as %, px, or rem with a new value;

text = "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
console.log(text.replace(/width ?: ?[0-9]+(%|[a-z]+|);/ig,"width:25%;"))

Answer №3

This code snippet will update any value starting with width and ending with %; within your string. Feel free to adjust the regular expression pattern as needed.

first = "width:90%;height:100%;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
second = "width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
third = "height:inherit;padding-right: 15px;padding-left: 15px;width:90%;margin-right: auto;margin-left: auto;"

console.log(first.replace(/width(.*?);/g,"width:25%;"))
console.log(second.replace(/width(.*?);/g,"width:25%;"))
console.log(third.replace(/width(.*?);/g,"width:25%;"))

Answer №4

If you need to change the numerical value from width:90px; to width:40px;

alternatively width:90%; can be updated to width:40%;

str = "max-width:40px;width:90px;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
console.log(str.replace(/([^-]width)(:[0-9]\d+)(.*)/g,"$1:25$3"))

str = "max-width:40px;width:90%;height:inherit;padding-right: 15px;padding-left: 15px;margin-right: auto;margin-left: auto;"
console.log(str.replace(/([^-]width)(:[0-9]\d+)(.*)/g,"$1:25$3"))

Answer №5

This specific code snippet width:[0-9]+%; is designed to locate a width value in percentage format, while the following part .*$ matches "anything that appears until the end of the string".

To prevent the second part from being replaced by width:25%;, it should be omitted:

oldStyle.replace(new RegExp("width:[0-9]+%;", "g"), "width:25%;")

This regular expression can definitely be refined. As noted by some individuals in the comments, it may unintentionally match instances like max-width:75% and modify them to max-width:25%. Despite this, depending on your specific requirements, it could suffice.

In general, considering the potential pitfalls involved, it's advisable to avoid using regular expressions in scenarios such as this unless absolutely necessary.

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

What is the reason why the show() function in JQuery only applies to one specific element, rather than all elements selected with the same selector?

JSFiddle. This example code features a nested <table> within another <table>. The main issue concerns the click listener for the #add button. Specifically, the final if/else statement in the function. When you execute this code and click the ...

The ng-click function within the template functions correctly initially, but ceases to work upon returning to the page

I am working on a Single page app website and I need the menu tab to change its class to active when a specific page is selected. The issue arises in my home.html template where I have an <a> tag linking to the history page. The goal is for the histo ...

Searching for an array of objects within a MongoDB collection using queries

I have a collection where I store information in an array of objects named Degrees. Each object in this array has keys like {Uni:'',Level:'',Degree:''}. I am trying to create a query that will help me find documents with a de ...

Unable to align span vertically using font-style "Luckiest Guy" in CSS

I have encountered an issue with vertically centering a span using the font-style "Luckiest Guy". https://i.sstatic.net/Lz8o3.png I attempted to use display: flex;align-items: center; on the span, but it did not work. App.vue <template> <div ...

Creating interactive tables in JavaScript with dynamic row adding, editing and deleting capabilities

Whenever I try to add a new row by clicking the Add Row button, an error occurs. My goal is to append a new 'tr' every time I click the add row button. Each 'td' should include a checkbox, first name, last name, email, mobile number, ed ...

What is the method for linking to another page ID using an <a href> tag?

On one of my pages, I have a section that references another page's div id to trigger a click event for editing specific form fields. This is the profile page: <a href="<?php echo base_url('settings_pro/edit'); ?>" name="pull-righ ...

The browser displays the jQuery ajax response instead of passing it to the designated callback function

I have a web application that connects to another web service and completes certain tasks for users. Using codeigniter and jQuery, I have organized a controller in codeigniter dedicated to managing ajax requests. The controller executes necessary actions ...

Can React components receive props or data when they are inserted into regular HTML code?

I have a project where I need to make updates to an old-fashioned website. The current layout is table-based and coded by hand. My idea to streamline the process is to use React to minimize repetitive coding tasks. Specifically, I want to loop through an a ...

How can we create a custom text search filter for month and date strings in Bootstrap-table2?

I'm working on a BootstrapTable that has a single column with a dataField of birthday, where the date is formatted as "day/month" (e.g. "3/10" for October 3rd). I managed to create a formatter that changes each string like "3/10" to display as "Octobe ...

The storage of HTML5 data is not being saved locally

<html> <head> <title></title> <style type="text/css"> body { font-family: tahoma; } h2 { font-weight: bold; border-bottom: 2px solid gray; margin-bottom: 10px; } #dat ...

Displaying an external webpage within a Backbone application

Is it feasible to display an external webpage in a view by using its URL? I am working with Backbone and Handlebars. var AuthorizeInstagramView = Backbone.View.extend({ template: Handlebars.compile(template), initialize: function () { }, ...

Is it possible to remove Google Markers?

I am facing an issue with rendering Markers on the map in my React component. Whenever I update the markers array, the new markers appear but the old ones remain on the map. For example, if I change the coordinates in the parent component, both the old and ...

Include images in the form of .png files within the td elements of a table that is dynamically generated in the index

I have successfully created a table using embedded JavaScript with the help of messerbill. Here is the code: <table id="Table1"> <tr> <th>Kickoff</th> <th>Status</th> <th>Country</th> < ...

When calling a function within a for loop, the function receives the final value instead of iterating through the sequence

I need assistance with setting unique names for objects in an array. I have the following setup: this.array = [{name: null}, {name: null}, {name: null}] Along with a list of reserved names: this.reserved = ["name2", "name3"] My goal is to loop through th ...

Arrange the columns in the Table in both ascending and descending order

While working on my React and MUI Table project, I encountered an issue with implementing sorting functionality for each column in both ascending and descending order. Whenever I click on the header to sort a column, an error message saying "Data is not it ...

Which directives in AngularJS facilitate one-way binding?

Which directives in AngularJS support one-way binding? While ng-model enables two-way binding, what about ng-bind and {{ }} expressions - do they also support one-way binding? ...

Tips for positioning a sticky div underneath a stationary header

I'm currently utilizing Bootstrap 4 for my project, and I am encountering an issue with maintaining a div that has the class "sticky-top" just below a fixed navbar. Despite attempting to use JavaScript to replace the CSS while scrolling, it hasn' ...

`Issues encountered while converting PHP Array to JSON format`

I've been encountering difficulties converting a multidimensional PHP Array to JSON. While using json_encode, the result is null. I'm working on developing an orgChart where the data is extracted from a CSV file and stored in an array. The layou ...

Mongoose: When attempting to cast the value "undefined" to an ObjectId at the _id path for the model "", a CastError occurred

I am working on developing an app using the MERN stack. However, I encountered an issue when trying to add a user to the current database. The error message reads as follows: CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model ...

AngularJS uses the syntax `Track by $index` to keep track

I'm currently working on incorporating different dates using a datepicker in my application. I have implemented a checkbox, and if the user checks that checkbox, then the dates are added. However, it appears that track by index is not functioning corr ...