Enhancing a Class using Jquery

It might sound strange, but I have a full URL as a class for some of my HTML elements. Obviously, this doesn't work for CSS purposes. What I want to achieve is to remove everything except the page slug. Here's an example of what I currently have:

<li class="menu-item http://example.com/page-link/">some code</li>

What I would like in terms of HTML output is this:

<li class="menu-item page-link">some code</li>

I thought about using the .replace method to get rid of "http://example.com/", but I'm unsure how to remove the trailing slash and the beginning of the URL. Here's my idea:

var strclass = $(li[class*=http://example.com/]).attr('class').match(/\bhttp://example.com/.+?\b/);
var newclass = strclass.replace("http://example.com/", "").replace("/", "");

Any assistance would be greatly appreciated. If the code above seems off-track, please point me in the right direction with helpful resources.

******I'm exploring new methods and seeking additional feedback!******

This is the updated code that combines some great suggestions:

if(li.hasClass('menu-item')) {
   var strclass = $('li.menu-item').attr('class');
   var newclass = strclass.split(" ")[1].split("/")[3];
   $(".menu-item").removeClass("http://example.com/" + strclass + "/").addClass(newclass);
}

The problem I am encountering now lies in the third line within the if statement where I try to replace the old class with the full URL with the new class containing only the page slug. If anyone has a solution or alternative approach, please share. Thank you all for your efforts and quick responses!

Answer №1

This code snippet accomplishes the task at hand:

var elements = document.querySelectorAll("li.menu-item");
alert(elements.length + " items with classes that require modification have been found.");

for(var i = 0 ; i < elements.length; ++i){
   var classes = elements[i].className.split(" ");
   elements[i].className = classes[0] + " " + classes[1].split("/")[3];
   alert("The new class attribute value is: " + elements[i].className);
}
.menu-item { font-family:Arial; font-size:1.5em; }
.page-link { background-color: red; }
.something {background-color: green;}
.go-somewhere {background-color: yellow; }
<li class="menu-item http://example.com/page-link/">some code</li>
<li class="menu-item http://example.com/something/">some code</li>
<li class="http://example.com/go-somewhere/">some code</li>
<li class="menu-item http://example.com/go-somewhere/">some code</li>

Answer №2

let originalString = "menu-item http://example.com/page-link/";
let newString = originalString.replace("http\:\/\/.+\/(.+)\/", "$1");

It might not address all your issues, but it seems like you're being too specific. Try using a more general pattern to replace that portion of the class string.

If you prefer a less greedy approach, only extracting the last folder:

let newString = originalString.replace("http\:\/\/.+\/([^\/]+)\/", "$1");

Answer №3

One way to create an array is by using forward slashes:

const words = sentence.split("/");

Next, you can find the specific word that represents either the end or second-to-last item in the array, depending on whether there is a closing slash.

if (words[words.length - 1]) {
  chosenWord = words[words.length - 1];
} else {
  chosenWord = words[words.length - 2];
}

Answer №4

If I were to handle this situation, I would utilize a regex pattern within a replace function like so: /.*?([^/]+)\/?$/

$('li[class*="http://"]').each(function(){
  var pattern = new RegExp('^https?://');
  var classes = this.className.split(' ');
  for(var i = 0, len = classes.length; i < len; i++) {
    if(pattern.test(classes[i])) {
      classes[i] = classes[i].replace(/.*?([^/]+)\/?$/, '$1');
    }
  }
  this.className = classes.join(' ');
});
.page-link {color: green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li class="menu-item http://example.com/page-link/">some code</li>
<li class="menu-item http://example.com/page-link/">some code</li>
<li class="menu-item http://example.com/page-link/">some code</li>

It is important to note that the regex in my solution accounts for both http and https protocols (excluding the //example.com/whatever/ syntax and relative urls), whereas the jQuery selector specifically targets only the http linked list items. It may be beneficial to create a separate class designation for this behavior, such as linked-list-item or a similar identifier.

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

Move a Java application from a trial SAP HCP to a complete SAP HCP membership

After successfully creating a Java IoT App with Raspberry Pi running on SAP HANA HCP trial account, I am now looking to enhance its functionality within the SAP HANA Development Workbench. Is there a way to import it into the SAP HANA account with ease, o ...

Determine the distance between two objects and the camera using Three.js

I am working with two squares positioned in space, resembling the front and back walls of a cube with specific vertices: x=-2 y=-1138 z=-2; x=-2 y=-1134 z=-2; x=2 y=-1138 z=-2; x=2 y=-1134 z=-2 The second square is defined by the following vertices: x=- ...

How to attach event to a button that is generated dynamically - Is live() the way

Currently utilizing a telerik grid control that showcases a grid with features such as paging, sorting, and filtering. Upon clicking the filter button on the grid, it triggers the appearance of the filter dialog. This dialog comprises a div containing inp ...

Are YUI CSS Fonts affected by %-based sizing when used in nested elements?

When utilizing YUI's CSS system, font-sizes are defined in percentages instead of pixels to ensure a consistent font size across different browsers. However, if you have elements with specified font sizes, any nested elements with font sizes set will ...

Tips for customizing the appearance of buttons in a JavaScript bxSlider

Take a look at my landing page: In the upper section, you'll find three buttons that allow you to switch between different slides. These buttons are named: credi5, credi10, and credi15. Now, I want to replace those buttons with images... specificall ...

inject spinner during the call and verify status post-call

How can I make the loading icon display during the save function call and then switch to the check mark icon after the function resolves instead of mocking it on a timeout? function save() { successMessage() new Promise((resolve, reject) => { setTim ...

Identifying the category of a value through a conditional check on another value

I am looking for my code editor to automatically determine the type of extraData based on the value of error, which is being narrowed down by an if statement: export enum ErrorCodes { Unknown = 'UNKWN', BadRequest = 'BDREQ', } int ...

Creating a Mongoose Schema for implementing the delete functionality

I'm having trouble deleting items from a MongoDB list. It seems that when the axios.delete method is called in the ExpensesListItem.tsx file, the item is not being deleted and no error message is displayed in the console. I suspect there might be an ...

Creating an innovative webpage that effectively showcases 11 unique elements, each with its own detailed description

In the process of creating a website, I have come across the task of designing a dedicated webpage that showcases 11 key elements representing the core values of the company. Each element comes with its own detailed description. The website layout includes ...

The automatic form completion feature in JavaScript failed to function

The last 2 rows starting from "request.done...." are not functioning correctly. Nothing happens when these lines of code run, even though everything else works perfectly Here is the script I am using: $(document).ready(function () { $('#retriev ...

Switching the visibility of rows in a table

Imagine this as my example table: <table> <tr> <td>a</td> <td>one</td> <td>two</td> </tr> <tr> <td>b</td> <td>three</td> <td>four</t ...

Attempting to increase by one with each visit to the page

I am currently working on a feature that updates a field by incrementing it by +1 every time the page is visited. If the page has never been visited before, I need to add it to the database as a new object in an array. However, my current implementation d ...

Leverage the power of npm packages within a Flutter mobile app's webview

I am currently developing a Flutter mobile app and I am interested in incorporating an npm package that utilizes web3.js and offers additional custom features. My understanding is that Dart code in Flutter is not compiled to JavaScript, so I have been lo ...

Is there a way to access hover effect information in Atom editor similar to how it appears in VScode?

Is there a specific plugin required in Atom to display information when hovering over variables, objects, or functions similar to intellisense? VSCode does this automatically, but I am looking for the same functionality in Atom. https://i.stack.imgur.com/ ...

Tips on implementing the onChange event in a custom text input for React Native applications

Recently, I started exploring React Native and attempted to create a custom text input with suggestions following a tutorial. However, I encountered an issue where I couldn't use onChange on my custom text input. I attempted to set up a state in App.j ...

Alignment of Material within Two Adjacent Divisions

I'm having trouble centering the content within two side-by-side divs. It seems like the content in each of these divs is centering towards one another, which is not what I want. I've created a main container and placed two divs inside it. The ...

Vue JS console displays an error stating "the <li> tag is missing a closing tag."

Below is the code snippet I am currently using to change the color based on the character's name: I encountered an error indicating that the li tag was not properly closed, although it appears to be closed. However, there seems to be an issue during ...

Unable to Retrieve Modified Content with $().text();

In the process of developing an app, I am encountering a challenge where I need to transfer user input to another element after processing it. However, I am facing an issue with accessing the updated value of the <textarea> using .text(), as it only ...

How can JavaScript be used to run a script only when the screen width is less than 480, and not when it is greater than 480?

Hi there, I have a simple script that I need help with. Despite not being well-versed in JavaScript, I am using Bourbon and Neat for the frontend of my website. On one particular page, I want to implement a collapse script from Bourbon refills. My question ...

Exploring how process.argv in NodeJS can be utilized within JavaScript code compiled by

I'm having trouble compiling a basic TypeScript file using webpack (with 'awesome-typescript-loader') that needs to access command line arguments. It seems like the compiled JavaScript is causing a problem by overriding the Node 'proce ...