Take a sequence of multiple words and combine them into a single string with hyphens in between

I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues when there are multiple words in the category name. Here is the code snippet:

 ( window.onload=function() {
   let cat =   document.querySelector('.cats').lastElementChild.textContent;
   let body = document.querySelector('body');  

   if(cat.indexOf(' ') >= 0) {
   cat.replace(' ','-');

   body.classList.add(cat.toLowerCase());
   } else {

   body.classList.add(cat.toLowerCase());
   }

   })();

For example, if the category is "dentist," it gets added as a string to the body tag. However, if the category is "General Doctor," it doesn't work properly.

I'm using functions.php to call this function only when it's a post by using if_single().

I tried using replace() to replace the space with a dash, but I seem to be implementing it incorrectly.

Is there a way I can transform something like "General Physician" into a string like "general-physician" so that it can be added as a class to the body tag?

Answer №1

Using the replace function, it will not alter the original value of the string. Give this a shot:

dog = dog.replace(/ /g,'_');

Answer №2

Initially, when using querySelector, it will only select the first matching element. If you need to check every element with the same class name, consider using querySelectorAll or getElementsByClassName.

Furthermore, regarding your inquiry, keep in mind that replace function will only replace the initial occurrence. To replace all instances, utilize:
cat.replace(/\s/g, "");

Moreover, remember to reassign the modified value:
cat = cat.replace(/\s/g, "");

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

Looking to create a format for displaying short comic strips in a grid pattern

I am struggling to create an image grid for my small comics. I want to have 2 columns and 3 rows, but all the divs end up in the same place. I tried using display: flex, but it didn't work as expected. Additionally, I want the grid to be responsive, b ...

Having trouble submitting a date input form generated with vuejs on Safari browser

I am a huge fan of Vuejs and it's my go-to at work. The other day, I came across a rather perplexing scenario. If you have any insights into this, please do share. Here is the code in question: <script setup lang="ts"> import { ref ...

Why does one image render while the other with the same src does not?

Has anyone encountered a situation where there are 2 img tags with the same src, "images/export.png", but one displays correctly while the other doesn't? Any insights on how this discrepancy can occur? Here's some background information: -The w ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...

Ways to fix the error message 'yarn package has unresolved peer dependency'

Whenever I run yarn upgrade or install, a bunch of warnings pop up due to unmet peerDependencies. warning " > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4322332c2f2f2c6e2f2a2d286e2b37373303726d766d7a">[email pro ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

The highlight_row function seems to be delayed, as it does not trigger on the initial onClick but works on subsequent clicks. How can I ensure it works properly right from the first click?

I developed an application using the Google JavaScript Maps API to calculate distances between addresses. I've encountered a bug where the row in the table is not highlighted on the first click, requiring a second click for the highlighting to take ef ...

My React application did not display properly after deploying it on GitHub Pages

I attempted to deploy my React app on GitHub Pages, but unfortunately it did not work as expected. When I tried to access the link, all I got was a blank page. Can anyone help me with a solution? Your assistance is much appreciated! Here's a snippet ...

Exploring Database with NodeJS, Express, and HTML

My goal is to create a basic web application using node.js where users can input data into a search bar and have that input sent to the server for database query. While I've successfully set up and connected my database, here's a glimpse of my co ...

A method designed to accept an acronym as an argument and output the corresponding full name text

Having trouble with my current task - I've got an HTML file and external JS file, and I need a function that takes an element from the 'cities' array as input and returns a string to be used in populating a table. I've set up a functio ...

What is the best way to include message body in CDATA using strophe?

I have a task to create messages in a specific format by using the following code: $msg({to: 'user', from: 'me', type: 'chat'}).c("body").t('some data'); This code generates the message structure as follows: <m ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...

How can a producer know when it's time to send a message in NodeJS using ZeroMQ?

After conducting some research on patterns supported by zeromq, I have encountered an issue with the PUB/SUB pattern in my recent project as well as the PUSH/PULL pattern. I am using NodeJS for the zeromq implementation. In my examples (server.js & client ...

What is the process for rendering a React class component using React HashRouter and Apollo client?

I've run into an issue with my project that involves using only React class components and fetching data from an Apollo server. The problem I'm facing is that, in Chrome, only the Navbar.jsx component is rendering. Even when I navigate to one o ...

Incomplete Json information

As I embark on my journey to learn Javascript and work on building an application simultaneously, I can't help but feel optimistic about the learning process. To guide me through this venture, I've turned to the teachings of Alex MacCaw in his bo ...

jQuery does not function properly when used with string variables

Why am I experiencing different results in Google Chrome when using a hard-coded string versus storing the same string in a variable? While the hard-coded string works properly, the same string stored in a variable does not produce the expected outcome. ...

What is the best way to extract text/html that appears between two consecutive <input> tags?

Is there a straightforward method to extract the text or HTML content located between input tags, even though these tags do not require closing tags? For instance, in the example below, I am looking to retrieve <b>Bob and Tim</b><br>Tim & ...

Pull information from database based on selection made in combo box

I am attempting to populate a text box with values from a database based on the selection in a combo box. I have written the code below but it doesn't seem to be working correctly. The issue is that the value selected in the combo box is not being pas ...

Having trouble retrieving prices using an npm package

There is a more effective way to retrieve prices using the npm package, node-binance-api, rather than relying on the "coin" variable that I am currently struggling with. If anyone could assist me in finding a better solution or the optimal method for fetch ...