How can I convert a string to PascalCase in JavaScript?
Antek N
antek n profile pic

To convert a string to PascalCase in JavaScript, you can follow these steps: 1. Remove any leading or trailing whitespace from the string. 2. Split the string into an array of words or tokens. You can use a regular expression to split the string by spaces, underscores, hyphens, or any other non-alphanumeric characters. 3. Capitalize the first letter of each word in the array. You can achieve this by iterating over the array and using thetoUpperCase() method to capitalize the first character of each word while keeping the remaining characters in lowercase. 4. Join the capitalized words back together to form a single string. You can use thejoin() method to concatenate the words with an empty string as the separator. Here's an example implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

function convertToPascalCase(str) {
  // Step 1: Remove leading/trailing whitespace
  str = str.trim();
  
  // Step 2: Split the string into words/tokens
  const words = str.split(/[\s_-]+/);
  
  // Step 3: Capitalize the first letter of each word
  const capitalizedWords = words.map(word => {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });
  
  // Step 4: Join the capitalized words
  const pascalCaseStr = capitalizedWords.join('');
  
  return pascalCaseStr;
}

// Example usage
const input = "hello_world";
const pascalCase = convertToPascalCase(input);
console.log(pascalCase);  // Output: "HelloWorld"

In this example, the input string "hello_world" is converted to PascalCase, resulting in "HelloWorld". You can modify the regular expression used in thesplit() method to handle different delimiters or customize the implementation according to your specific requirements.