convert a string to camel case in typescript

One way to convert a string to camel case in TypeScript is by using regular expressions and the replace function. Here's an example function that takes a string and returns a camel-cased version of that string:

function toCamelCase(str: string): string {
  return str.replace(/([-_][a-z])/ig, ($1) => {
    return $1.toUpperCase()
      .replace('-', '')
      .replace('_', '');
177 chars
8 lines

In this function, we use regular expressions to match any hyphens or underscores followed by a lowercase letter. We then use the replace function to replace each match with the uppercase version of the matched letter (without the hyphen or underscore). This effectively converts the string to camel case.

Here's an example usage of the function:

const myString = 'hello_world-how_are_you';
const myCamelCaseString = toCamelCase(myString);
console.log(myCamelCaseString); // Outputs: "helloWorldHowAreYou"
159 chars
4 lines

Note that this implementation assumes that the input string has no spaces. If spaces are present in the input string, the regular expression will need to be adjusted to handle them appropriately.

gistlibby LogSnag