Is it possible to transform the string "folder/lower-case-with-dash" into "folderLowerCaseWithDash" (in camelCase format) using regular expressions?

I've been grappling with creating a function that transforms a string into "camelCase" format. At the moment, the function capitalizes letters following a hyphen - and eliminates the hyphens entirely.

Here is the existing function:

function camelCase(str) {
  return str.replace(/-([a-z])/g, g => {
    return g[1].toUpperCase()
  })
}

The string provided to the str parameter may contain single forward slashes / and hyphens - alongside alphabetical characters.

I've experimented with various regex combinations in an attempt to solve this issue, but I seem to be stuck. How can I modify the regular expression /-([a-z])/g to also exclude forward slashes?

// CURRENT OUTPUT
console.log(camelCase("folder/lower-case-with-dash"))
// folder/lowerCaseWithDash
// DESIRED OUTPUT
console.log(camelCase("folder/lower-case-with-dash"))
// folderLowerCaseWithDash

Your assistance on this matter would be greatly appreciated.

Answer №1

Make sure to use a character set that includes the forward slash ("/") so that both hyphen "-" and forward slash "/" are matched at the beginning of the string:

function convertToCamelCase(str) {
  return str.replace(/[\/-]([a-z])/g, match => {
    return match[1].toUpperCase()
  })
}

console.log(convertToCamelCase("folder/lower-case-with-dash"))

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

The onchange event for the input type=file is failing to trigger on Google Chrome and Firefox

Update: Solved: http://jsfiddle.net/TmUmG/230/ Original question: I am facing an issue with handling image/logo upload alongside a hidden input type=file: <form class="image fit" id="theuploadform"> <input title="click me to chan ...

Tips for customizing Material UI Tooltip styles

Is there a way to customize the appearance of the Material UI Tooltip title? I have noticed that by default, the tooltip displays with a black background and no text wrap on hover. Can the background color, text color, and other styles be modified? Wonde ...

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...

Retrieving information from one controller to another controller

I have been tasked with developing an application using angularjs. The application consists of a login page and home page. The layout is divided into two sections - header and container, each controlled by headerCtrl and loginCtrl respectively. The heade ...

In a multi-user environment, querying FaunaDB may not always retrieve the most up-to-date results

Background I've been delving into FaunaDB alongside React and managed to create some code with inspiration from this article. The project I'm working on involves a coffee poll/counter app - users are presented with various types of coffee and ca ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

Using Jquery and the cookie.split method to extract and eliminate a value from a cookie

I am trying to figure out how to remove a specific matching value from a cookie using JavaScript. I have written a script that loops over the cookie and checks for matches, but I can't seem to successfully remove just the matching value. Any tips on a ...

Is there a way to automatically scroll the parent page's top when the user navigates within an iframe?

We are encountering an issue with the loading of the iFrame. When the iFrame loads on the client's page, we notice that the page location jumps around and, in most cases, the page focus is lower down the page. This requires users to scroll up to view ...

The concatenation function in JavaScript does not seem to be functioning properly with JSON

My attempt to use .concat() in order to combine two objects is resulting in tiles.concat is not a function The following code (in an angular app and written in coffeescript): $scope.tiles = new UI(); $scope.tiles.loadUITiles(); console.log($sco ...

In regards to the preceding element within an array composed of strings

Recently, I've started learning Java and I've encountered a challenge with arrays. Below is the code that I'm currently working on. String english = "hip-hop"; String[] words = english.split ("[\\s+]|(?<=-)|(?=-)"); Str ...

Using JavaScript promises to handle connection pooling and query execution

I am contemplating whether this approach is on the right track or if it requires further adjustments. Should I consider promisifying my custom MySQL getConnection method as well? request: function(queryRequest) { return new Promise(function(re ...

The use of multiple Where clauses in a Firestore Firebase query is not functioning as expected when implemented in JavaScript code

https://i.stack.imgur.com/DdUGj.png db.collection('User_Info').where("User_Name", "==", "Sam").where("PASSWORD", "==", "c2FtMTIzQA==").get().then(snapshot => { if(snapshot.docs.length > 0 ){ debugger; alert("Login Successful."); ...

Tips for showing HTML content in an Angular UI grid

I've been attempting to showcase HTML within the grid by checking out this resource: Add html link in anyone of ng-grid However, my attempts led me to this code snippet: var app = angular.module('myApp', ['ngGrid']); ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Error: An unexpected token '<' was encountered during the React Webpack build process

My ReactJs project is using Webpack4 and @babel/core 7. However, when I attempt to build the project, I encounter the following error in the terminal: ERROR in ./src/views/Pages/Login/Login.js Module build failed (from ./node_modules/babel-loader/lib ...

Lodash: the art of simplification

What is the best way to streamline the following code: rules = rules.map(rule => Object.assign(rule, rule.ruleOption.options)) rules.forEach(rule => delete rule.ruleOption) rules = _.keyBy(rules, 'code') I have recently started using Loda ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

Connecting a Vue js model data to a Select2 select box

Utilizing select2 to improve an html select element, I am facing challenges in binding the value of the select element to a Vue variable because Select2 appears to be causing interference. Is there an optimal approach to achieve this data binding and even ...

Crafting dynamic parameters in the Express router - A step-by-step guide!

Original Code Example: const express = require('express'); const router = express.Router(); router.get('/data/:d1/:d2/:d3', require('../apifoo').foo); Route: /data/:d1/:d2/:d3 Path: /data/1/2/3 req.params : 'd1' : ...

utilizing different types of text style

Whenever I write a paragraph, I want the text to be styled like this: Click here for alt text http://img6.imageshack.us/img6/9894/fullscreencapture282010.jpg Do I need to use CSS to achieve this kind of formatting? I'd like it to look similar. ...