Table of Contents
Use String.replace() method
Example
Use Array.map() and Array.join() methods
Home Web Front-end JS Tutorial How to convert hyphens to camelCase in JavaScript?

How to convert hyphens to camelCase in JavaScript?

Sep 05, 2023 am 10:21 AM

如何在 JavaScript 中将连字符转换为驼峰式大小写?

As developers, we often encounter hyphenated strings. Hyphenated strings make our code more readable when string lengths are long and names are very complex. To solve this problem we use camel case. CamelCase is a very popular naming convention in which we combine multiple words and form a string by capitalizing the first letter of each string except the first. In javascript, we can use this convention to create variable and function names, but we cannot use hyphenated strings to create variables. In this article, we'll step through the various methods of converting hyphens to camelCase. By the end of this article, you will be able to apply techniques to improve the readability and maintainability of your code.

Here are some examples of converting hyphens to camelCase -

Input: this-is-an-object 
Output: thisIsAnObject
Input: convert-hyphens-to-camel-case
Output: convertHyphensToCamelCase
Copy after login

Here are a few ways to convert hyphens to camelCase using JavaScript.

  • Use String.replace() method

  • Use Array.map() and Array.join() methods

Use String.replace() method

String.replace method is a built-in method in javascript, used to replace the specified value with another value in the string. The following is a step-by-step procedure for converting a hyphenated string to a camelCase string using the String.replace method.

  • Use the first parameter of the String.replace method to search for all letters following a hyphen.

  • You can use regular expressions such as /-([a-z])/g

  • This regular expression selects two elements, the first is a hyphen and the second is the letter after the hyphen.

  • In the second parameter of the String.replace method, return the uppercase value of the second letter.

Example

In this example, we use the String.replace method to convert a hyphenated string to camelCase format.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Converting Hyphenated string into Camel case string in JavaScript</title>
</head>
<body>
   <h3>Converting Hyphenated string into Camel case string using String.replace() method</h3>
   <p id="input">String with hyphens: </p>
   <p id="output"> String after converting hyphens to camel case: </p>
   <script>
      // The input String
      let inp = "this-is-an-object";
      document.getElementById("input").innerHTML += inp;
      
      // Search for the letter after the hyphen and return the uppercase value
      inp = inp.replace(/-([a-z])/g, function(k){
         return k[1].toUpperCase();
      })
      
      // Print the camel case value
      document.getElementById("output").innerText += inp;
   </script>
</body>
</html>
Copy after login

Use Array.map() and Array.join() methods

The Array.map() method is JavaScript that creates a new array after applying a function in each element of the array. This method does not modify the original array.

Array.join method is used to convert an array into a string by joining all elements of the array.

To convert a hyphenated string to a camel case string, we use the following steps.

  • Split array elements from each hyphen using the String.split method. Now we have an array which contains all the words of String as array elements.

  • Now use the Array.map and String.toUpperCase methods to convert the first letter of each element to uppercase.

  • Now use the Array.join method to join the Arary elements. Finally, we get the camel case string.

Example

In this example, we convert the hyphenated string to camelCase string.

<html>
<head>
   <title>Converting Hyphenated string into Camel case string in JavaScript</title>
</head>
<body>
   <h3>Convert Hyphenated string into Camel case string using Array.map() and Array.join() methods</h3>
   <p id="input">String with hyphens: </p>
   <p id="output"> String after converting hyphens to camel case: </p>
   <script>
      // The input String
      let inp = "this-is-an-object";
      document.getElementById("input").innerHTML += inp;
      
      // Convert the String into an Array
      inp = inp.split("-");
      
      // Remove and save the first element
      let firstString = inp.shift();
      
      // Convert every first letter into uppercase
      inp = inp.map(function(k){ 
      return k[0].toUpperCase() + k.substring(1);
      });
      
      // Join the Array
      inp = inp.join("");
      
      // Concatenate the first element 
      inp = firstString + inp;
      
      // Print the camel case value
      document.getElementById("output").innerText += inp;     
   </script>
</body>
</html>
Copy after login

The above is the detailed content of How to convert hyphens to camelCase in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles