简体   繁体   中英

How to convert string to camelCase without using RegEX

I'm trying to do a challenge which is converting all strings into camelCase but without using regex, only using the methods like(split, slice, replace, includes.. etc). Some words have spaces and should remove them. Here's the CODE and I'm really STUCK. NOTE: the user enters the STRING and when user clicks the button should return to the camelCase.

INPUT => //underscore_case //first_name //Some_Variable // calculate_AGE //delayed_departure

OUTPUT => //underscoreCase //firstName //someVariable //calculateAge //delayedDeparture

document.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));

document.querySelector('button').addEventListener('click', function() {
  const text = document.querySelector('textarea').value;
  const row = text.split('\n');
  let [...n] = '';
  for (const theText of row) {
    const lowerText = theText.toLowerCase().trim();
    if (lowerText.includes('_')) {
      n = lowerText.replace('_', ' ');
      console.log([...n]);
    }
  }
});

Explanation of this simple algorithm:

  1. Your input must have words that split by a certain character, as you need something to identify which part of the string is a word. Let's assume your string has words separated by '//' instead of spaces as you mentioned in the comments, and each of those words is split by '_'.

  2. First you need to split all words in the string into an array, you can use the split() method in order to do that.

  3. Then when iterating through each word, split it again with split() but this time with whatever identifies the different words, in our case it's _ .

  4. Iterate through each split words, if it's the first word lowercase it using toLowerCase() and add it to the new word variable, if not, lowercase it and capitalize the first letter.

And that's it. Here's the implementation:

 const inputWithoutCamelCase = 'hello_world // HOW_ARE_YOU // foo_BAR' function stringToCamelCase(string) { const allNames = string.split('//') let camelCasedString = ''; for (const name of allNames) { camelCasedString += nameToCamelCaseHelper(name); } return camelCasedString; } function nameToCamelCaseHelper(word) { const splittedName = word.split('_'); let camelCasedName = ''; for (let i = 0; i < splittedName.length; i++) { if (i === 0) { camelCasedName += splittedName[i].toLowerCase(); } else { camelCasedName += capitalizeFirstLetter(splittedName[i].toLowerCase()) } } return camelCasedName; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } stringToCamelCase(inputWithoutCamelCase) // helloWorld howAreYou fooBar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM