首页 > 解决方案 > 如何在javascript中交换大写和小写字母?

问题描述

我的程序必须更改我在UpperCaseLowerCase上的大小写。

例子:

词:“cAP”

解决方案:“大写”

都很好,但是。

我的程序用一个词效果很好。

该程序通过两个第一个符号(大写或小写)检查我的单词的大小写但是当处理句子时我遇到了问题。

我不明白,我必须使用什么方法。也许需要使用数组或循环来执行此操作?

我的问题:

词:“为什么我们需要大写锁定?”

我的程序代码:

let newWord = 'cAPS'
word = newWord

if (word.length > 1) {
  var lengthWord = word.length
  if (word.substring(1) == word.toUpperCase().substring(1)) {
    newWord = word.toUpperCase(0, 1).substring(0, 1) +
      word.toLowerCase().substring(1)
    console.log(newWord)
  } else if (word.substring(0) == word.toUpperCase().substring(0)) {
    newWord = word.toLowerCase().substring(0)
    console.log(newWord)
  } else if (word.substring(0, 1) == word.toUpperCase().substring(0, 1)) {
    newWord = word
    console.log(newWord)
  }

}

标签: javascript

解决方案


其简单易行的方法是转换每个单词的字符串大写。

var mystring = "wHY DO wE NEED cAPS lOCK"
var mystring_split = mystring.split(" ")
complete = []

mystring_split.forEach(myFunction);
 function myFunction(item, index) {
   word= item
  if (word.length > 1)
{
var lengthWord = word.length
if (word.substring(1) == word.toUpperCase().substring(1)) {
   newWord = word.toUpperCase(0, 1).substring(0, 1) + 
   word.toLowerCase().substring(1)
   complete.push(newWord)
}
return complete

}
}

console.log( complete.join(" "))


推荐阅读