w3resource

JavaScript: Convert a string from camelcase

JavaScript fundamental (ES6 Syntax): Exercise-229 with Solution

Write a JavaScript program to convert a string from camelcase.

  • Use String.prototype.replace() to break the string into words and add a separator between them.
  • Omit the second argument to use a default separator of _.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const fromCamelCase = (str, separator = '_') =>
  str
    .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
    .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
    .toLowerCase();

console.log(fromCamelCase('someDatabaseFieldName', ' '));
console.log(fromCamelCase('someLabelThatNeedsToBeCamelized', '-'));
console.log(fromCamelCase('someJavascriptProperty', '_'));

Sample Output:

some database field name
some-label-that-needs-to-be-camelized
some_javascript_property

Pictorial Presentation:

JavaScript Fundamental: Convert a string from camelcase.
JavaScript Fundamental: Convert a string from camelcase.

Flowchart:

flowchart: Convert a string from camelcase.

Live Demo:

See the Pen javascript-basic-exercise-229-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to log the name of a function.
Next: Write a JavaScript program to get the human readable format of the given number of milliseconds.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.