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-neveropen-for-neveropen" ; console.log( "original string:" + str); function gfg_Run() { console.log(str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); })); } gfg_Run() |
original string:this-is-neveropen-for-neveropen 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-neveropen" ; console.log( "original string:" + str); function gfg_Run() { console.log(str.replace(/-([a-z])/g, function (m, s) { return s.toUpperCase(); })); } gfg_Run() |
original string:-a-computer-science-portal-for-neveropen 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-neveropen - computer - science - portal -for-neveropen" function convert() { const hyphen = hyphenText.trim(); const camel = converter(hyphen); console.log(camel); }; convert() |
geek ForGeeks computer science portal ForGeeks