跳转至

Coding Challenge #4#

Write a program that receives a list of variable names written in underscore_case and convert them to camelCase.

The input will come from a textarea inserted into the DOM (see code below to insert the elements), and conversion will happen when the button is pressed.

Test data (pasted to textarea, including spaces)#

1
2
3
4
5
underscore_case
 first_name
Some_Variable
  calculate_AGE
delayed_departure

Should produce this output (5 separate console.log outputs)#

1
2
3
4
5
underscoreCase      ✅
firstName           ✅✅
someVariable        ✅✅✅
calculateAge        ✅✅✅✅
delayedDeparture    ✅✅✅✅✅

Hints#

  • Remember which character defines a new line in the textarea 😉
  • The solution only needs to work for a variable made out of 2 words, like a_b
  • Start without worrying about the ✅. Tackle that only after you have the variable name conversion working 😉
  • This challenge is difficult on purpose, so start watching the solution in case you're stuck. Then pause and continue!

Afterwards, test with your own test data!

Starter Code#

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

GOOD LUCK 😀


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ocument.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));
document.querySelector('textarea').value = `
underscore_case
first_name
Some_Variable
calculate_AGE
delayed_departure
`

document.querySelector('button').addEventListener('click', function () {
    const text = document.querySelector('textarea').value;
    const rows = text.split('\n');
    let validrow = 0;
    for (const row of rows) {
        // 跳过空行
        const trimmedRow = row.trim()
        if (!trimmedRow) continue

        validrow++
        const [first, second] = row.toLowerCase().trim().split('_')
        const str = first + second.replace(second[0], second[0].toUpperCase())
        // padEnd 只传一个参数会在文本后填空格到指定位置
        console.log(`${str.padEnd(20)}${'✅'.repeat(validrow)}`)
    }
})

评论