Javascript to camel case

JavaScript Challenge 6: Convert string to camel case

In this article we will solve together the Convert string to camel case challenge from CodeWars, you can find it at this link. The difficulty of this challenge is easy. Let’s read the task together:

Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). Examples
toCamelCase(«the-stealth-warrior») // returns >»theStealthWarrior» toCamelCase(«The_Stealth_Warrior») // returns «TheStealthWarrior»

The easiest way to solve this challenge will be with RegEx and we don’t even need a complicate one in this case:

Write the RegExp

  • [-_] will match all the underscore and dashes
  • \w will match any character right after a dash or underscore
  • /ig will perform a global case insesitive search.

The trick that will help us complete the challenge more easily is the \w which allows us to capture the letter right after a dash or underscore, meaning we can easily make it uppercase in one go.

When you want to play around with RegEx, this is a great playground that also explains how they work regexr.com.

Now that we have the most important piece of our function, let’s try and build a function around it.

function toCamelCase(str) const regExp = /[-_]\w/ig; return str.replace(regExp,(match) =>  console.log(match); >); > toCamelCase("the-stealth-warrior") // -s // -w 

String.replace() can take not only a substring but only a RegExp as the first parameter and will pass the result in the second one.

As you can see our RexExp matched each dash and the first character after.

Completing the function

Now what we are left to do with the function is to return only the uppercase letter without the dash or underscore.

function toCamelCase(str) const regExp = /[-_]\w/ig; return str.replace(regExp,(match) =>  return match[1].toUppercase() >); > toCamelCase("the-stealth-warrior") 

That’s it, the last line we added will return S instead of -s and W instead of -w.

here are many other ways of solving this problem, let me know yours in the comment.

If you liked this type of content, please let me know in the comments and I’ll create more of these.

If you want to learn everything about JavaScript from ES6 all the way to ES2020, please check out my book available to read for free on Github. A course is also on Educative

Источник

How to Convert Any String into Camel Case with JavaScript?

white and brown shih tzu puppy

Sometimes, we want to convert a JavaScript string into camel case with JavaScript.

In this article, we’ll look at how to convert any string into camel case with JavaScript.

Use the String.prototype.replace method

We can use the string instances’ replace method to convert each word in the string to convert the first word to lower case, the rest of the words to upper case, then remove the whitespaces.

const camelize = (str) => < return str.replace(/(?:^\w|\[A-Z\]|\b\w)/g, (word, index) =>< return index === 0 ? word.toLowerCase() : word.toUpperCase(); >).replace(/\s+/g, ''); > ` console.log(camelize("EquipmentClass name")); 

We call replace with a regex that looks for word boundaries with \b and \w .

\w matches any alphanumeric character from the Latin alphabet.

We check the index to determine if it’s the first word or not.

If it’s 0, then we return word.toLowerCase() to convert it first character of the word to lower case since it’s the first word.

Otherwise, we return word.toUpperCase to convert the first character of the word to upper case.

Then we call replace again with /\s+/g and an empty string to replace the spaces with empty strings.

Therefore, camelize returns ‘equipmentClassName’ as a result.

Lodash camelCase Method

We can use the Lodash camelCase method to convert any string to camel case the same way the camelize function does.

For instance, we can write:

console.log(_.camelCase("EquipmentClass name")); 

Then we get the same result as the previous example.

Conclusion

We can convert any JavaScript string to camel case with the String.prototype.replace method or the Lodash camelCase method.

Источник

johnsmith17th / camelCase.js

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

function toCamelCase ( str )
return str . toLowerCase ( ) . replace ( / (?: ( ^ . ) | ( \s + . ) ) / g , function ( match )
return match . charAt ( match . length — 1 ) . toUpperCase ( ) ;
> ) ;
>

I need to put space between string Eg: Current String «HelloWorld» , I need «Hello World»
could you please help me in this ?

Note this JS doesn’t appear to work (at least not to covert snake or kebab case to camel case. Appears to want to convert a space delimited string.

This is Pascal Case (PascalCase), not Camel Case (camelCase). In other words, camel case is when the first letter is lower case.

function toCamelCase(string) < string = string.toLowerCase().replace(/(?:(^.)|([-_\s]+.))/g, function(match) < return match.charAt(match.length-1).toUpperCase(); >); return string.charAt(0).toLowerCase() + string.substring(1); > 

Small changes to the above to allow for kebab and snake case input, as well as proper camelCase rather than PascalCase as @mcarlucci pointed out.

EDIT: I tried the gist from @assembledadam above but it did not seem to work for me.

You can’t perform that action at this time.

Источник

How to convert any string to camelCase in JavaScript

Converting a string to camelCase should be easy in Node.js or web environments using JavaScript. There are many ways to solve this problem, with and without external dependencies.

There are many ways to achieve these things. We will look first at the no-dependency version and then present you many alternatives that are a lot better tested.

Without Dependencies

Dependencies are not often needed for a lot of use-cases. So let us explore options without external dependencies.

With ECMAScript 6+ (ES6)

1const toCamelCase = text =>  2 return text 3 .replace(/(?:^\w|[A-Z]|\b\w)/g, (leftTrim, index) => 4 index === 0 ? leftTrim.toLowerCase() : leftTrim.toUpperCase(), 5 ) 6 .replace(/\s+/g, ""); 7 >; 8 9 // Usage 10 toCamelCase("SomeClass name"); // => someClassName 11 toCamelCase("some className"); // => someClassName 12 toCamelCase("some class name"); // => someClassName 13 toCamelCase("Some Class Name"); // => someClassName 14 

This is probably the most most common technique top convert strings to camelCase. First a replace function is getting called on the string and splits the string first by the dividing characters and then uppercases the first character of each part except it is the first occurrence.

A small detail to remember is that the splitting function works for most white spaces but will not work on any other case like hyphens or different case types.

With TypeScript

1export const toCamelCase = (text: string): string =>  2 return text 3 .replace(/(?:^\w|[A-Z]|\b\w)/g, (leftTrim: string, index: number) => 4 index === 0 ? leftTrim.toLowerCase() : leftTrim.toUpperCase(), 5 ) 6 .replace(/\s+/g, ""); 7 >; 8 9 // Usage 10 toCamelCase("SomeClass name"); // => someClassName 11 toCamelCase("some className"); // => someClassName 12 toCamelCase("some class name"); // => someClassName 13 toCamelCase("Some Class Name"); // => someClassName 14 

The TypeScript example basically works the same as the example above. It splits the string and upppercases or lowercases the first character. But this time with type defintions!

With lodash

Another alternative is to use a package that might be already in your codebase called lodash. Lodash is an utility library that mostly gets introduced because of its great array functionalities. But one functionality often overlooked is the ability to convert case types.

1const _ = require("lodash"); 2 3_.camelCase("Foo Bar"); // => 'fooBar' 4_.camelCase("--foo-bar--"); // => 'fooBar' 5_.camelCase("__FOO_BAR__"); // => 'fooBar' 6 

As you can see in the code example it is working flawless. It is well supported and supports a lot more case types than the solution above.

With change-case (npm package)

Another external package that you can use is change-case. change-case is written in TypeScript and only focuses on converting case types. It is a great utility package that is also used heavily by this website for conversions. In comparison to the lodash alternative it supports many more cases like:

1import  camelCase > from "change-case"; 2 3 camelCase("test string"); // => "testString" 4 camelCase("test_string"); // => "testString" 5 camelCase("TestString"); // => "testString" 6 

Usability by this library is so easy and it does what it promises. It converts the string. Hooray!

With ECMAScript 5 (ES5)

If you are working in an older environment you also might need a version to convert to camelCase without fancy arrow functions and other ECMAScript 6+ features. For that we can use the version below.

1function formatCase(leftTrim, index)  2 return index === 0 ? leftTrim.toLowerCase() : leftTrim.toUpperCase(); 3 > 4 5 function toCamelCase(text)  6 return text.replace(/(?:^\w|[A-Z]|\b\w)/g, formatCase).replace(/\s+/g, ""); 7 > 8 9 // Usage 10 toCamelCase("SomeClass name"); // => someClassName 11 toCamelCase("some className"); // => someClassName 12 toCamelCase("some class name"); // => someClassName 13 toCamelCase("Some Class Name"); // => someClassName 14 

Converting the keys of an object to camelCase

Another use case that you might want to have a solution for is changing the keys of an object to camelCase. In the last blog article we explained in a short format on how to change any case of object properties in JavaScript.

It is actually quite easy to convert every object key. You just have to traverse every key in an object and map arrays when they occur. This should cover most of the standard use cases in the JavaScript and TypeScript world. So let us check how to do this.

1const  camelCase > = require("change-case"); 2 3 const isObject = o =>  4 return o === Object(o) && !Array.isArray(o) && typeof o !== "function"; 5 >; 6 7 const changeCase = entity =>  8 if (entity === null) return entity; 9 10 if (isObject(entity))  11 const changedObject = >; 12 Object.keys(entity).forEach(originalKey =>  13 const newKey = camelCase(originalKey); 14 changedObject[newKey] = changeCase(entity[originalKey]); 15 >); 16 return changedObject; 17 > else if (Array.isArray(entity))  18 return entity.map(element =>  19 return changeCase(element); 20 >); 21 > 22 23 return entity; 24 >; 25 26 const sourceJson = ''; 27 const sourceObject = JSON.parse(sourceJson); 28 29 const result = changeCase(sourceObject); // Will be 30 

As I said this will not cover special data structures like Maps, Sets and similar but will work for most common data structures. We have also decided to use change-case because it would help you to change the target case later on quite simply.

Источник

Читайте также:  Javascript for database query
Оцените статью