查找大写字母

问题描述 投票:0回答:1

我试图找到大写字母并在它们之前放置一个空格以将字符串切成单词,但不是获取所有大写字母并插入空格,而是在找到第一个字母后每隔相同数量的字母插入空格。就像如果是“camelCasingTest”,结果将是“camel Casin gTest”

function camelCase(string) {
    let splittedString = string.split('')

    for(let i = 0; i < splittedString.length; i++){
       if(string.charAt(i) === str.charAt(i).toUpperCase()){
        splittedString.splice(i, 0, ' ')
        // i - where the change should be
        // 0 - how many elements should be removed
        // " " - what element should be inserted
        i++
        // The i++ statement ensures that the loop skips the inserted space and continues to the next character.
       }
    }
    return splittedString.join('')
}

我尝试使用正则表达式并且它有效,但是这个问题困扰着我,有什么建议吗?

javascript arrays algorithm uppercase camelcasing
1个回答
0
投票

您的比较应该使用新数组而不是源字符串。否则,当您将索引注入数组时,您会发生漂移。

function camelCase(str) {
  const chars = str.split('')
  for (let i = 0; i < chars.length; i++) {
    // check the array rather than the original string
    if (chars[i] === chars[i].toUpperCase()) {
      chars.splice(i, 0, ' ')
      i++
    }
  }
  return chars.join('');
}
console.log(camelCase('camelCasingTest'));

© www.soinside.com 2019 - 2024. All rights reserved.