Open In App

How to convert hyphens to camel case in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a string containing hyphens (-) and the task is to convert hyphens (-) into camel case of a string using JavaScript.

Approach: 

  • Store the string containing hyphens into a variable.
  • Then use the RegExp to replace the hyphens and make the first letter of words upperCase.

Example 1: This example converts the hyphens (‘-‘) into camel case by using RegExp and replace() method.  

Javascript




let str = "this-is-geeks-for-geeks";
 
console.log("original string:" + str);
 
function gfg_Run() {
    console.log(str.replace(/-([a-z])/g,
        function (g) { return g[1].toUpperCase(); }));
}
gfg_Run()


Output

original string:this-is-geeks-for-geeks
thisIsGeeksForGeeks

Example 2: This example is quite similar to the previous one and converts the hyphens (‘-‘) to the camel case by using RegExp and replace() method.

Javascript




let str = "-a-computer-science-portal-for-geeks";
 
console.log("original string:" + str);
 
function gfg_Run() {
    console.log(str.replace(/-([a-z])/g,
        function (m, s) {
            return s.toUpperCase();
        }));
}
gfg_Run()


Output

original string:-a-computer-science-portal-for-geeks
AComputerSciencePortalForGeeks

Example 3: In this example, The HTML document has a container with a header, a paragraph labeled “text” containing a hyphen-separated string, and a button labeled “btn”. When the button is clicked, a function called “converter” converts the string to camel case and sets it as the text content of the paragraph. The “converter” function splits the hyphenated string into an array of words, maps over it to convert each word to camel case, and then joins the words together with an empty string separator.

Javascript




const converter = (str) => {
    return str.split('-').map((word, index) => {
        if (index === 0) {
            return word;
        }
        return word.charAt(0).toUpperCase() + word.slice(1);
    }).join('');
};
 
const hyphenText = "geek -for-geeks - computer - science - portal -for-geeks"
 
function convert() {
    const hyphen = hyphenText.trim();
    const camel = converter(hyphen);
    console.log(camel);
};
convert()


Output

geek ForGeeks  computer  science  portal ForGeeks


Last Updated : 05 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads