Camelcase String With JavaScript

Paulund
Oct 1, 2022

--

In this tutorial we’re going to change a string of words to be camel-cased.

You can do this by using the below regex to select all the matched parts of the string and then on the first index you lowercase the word and on the next indexes you can make uppercase.

export const camel = (text: string): string => {
return text.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // if space
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}

This will allow you to take the following scenarios and camel-case the response.

import {camel} from "./camel";test('it will camelcase text', () => {
expect(camel('CamelCaseClassName')).toBe('camelCaseClassName')
expect(camel('Camel Case Class Name')).toBe('camelCaseClassName')
expect(camel('Camel CaseClassName')).toBe('camelCaseClassName')
expect(camel('camel case class name')).toBe('camelCaseClassName')
expect(camel('CamelCase ClassName')).toBe('camelCaseClassName')
expect(camel('CamelCaseClass Name')).toBe('camelCaseClassName')
});

Camel Function

Originally published at https://paulund.co.uk.

--

--

Paulund
Paulund

No responses yet