3
        <script type='text/javascript'>
        function redirect() {
            var input = document.getElementById('userInput').value;
            switch(input) {
                case 'ALCOA':
                    window.location.replace('alcoa-Forms.htm');
                    break;
                case 'alcoa':
                    window.location.replace('/alcoa-Forms.htm');    
                    break;

この関数で大文字と小文字が区別されないようにするにはどうすればよいですか?

4

6 に答える 6

9

最も簡単な方法は、入力をすべて大文字またはすべて小文字にすることです。好きなのを選びな:

input = input.toUpperCase();
switch (input) {
   case 'ALCOA':
      ...

Alcoaこれは、aLcOaなどでも機能することに注意してください。

case2回書くこともできます:

switch (input) {
   case 'ALCOA':
   case 'alcoa':
于 2013-01-07T17:58:42.270 に答える
3

入力を大文字にします:

<script type='text/javascript'>
    function redirect() {
        var input = document.getElementById('userInput').value;
        input = input.toUpperCase()
        switch(input) {
            case 'ALCOA':
                window.location.replace('alcoa-Forms.htm');
                break;
于 2013-01-07T18:00:13.080 に答える
2

.toLowerCase()(または) が最も簡単.toUpperCase()な方法ですが、正規表現の方法もあります。

if (/^alcoa$/i.test(input)) {
    // ...
}
于 2013-01-07T18:10:55.153 に答える
2

入力を小文字または大文字に変換する必要があります。例えば:

var input = document.getElementById('userInput').value.toLowerCase();
于 2013-01-07T17:58:51.437 に答える
2

.toLowerCase() または .toLocaleLowerCase() を使用してください。これらの関数は、トルコ語などの言語のいくつかのあいまいな例外とほぼ同じであることに注意してください。

コード

function redirect() {
     var input = document.getElementById('userInput').value.toLowerCase();
     switch (input) {
        case 'alcoa':
            window.location.replace('alcoa-Forms.htm');
            break;
    }
}

より詳細な

関数は「大文字と小文字を区別」しません。むしろ、コードでは大文字と小文字が区別されます。この問題を回避する方法は、結果を確認する前に入力を 1 つのケースに正規化することです。これを行う 1 つの方法は、チェックする前に文字列をすべて小文字に変換することです。

代替ソリューション

ケース フォールスルー構文を使用します。

switch(text) { 
     case 'a':
     case 'A':
         doSomething();
}
于 2013-01-07T18:00:07.940 に答える
1

toUpperCase() を使用する場合、switch(input) 関数内のケース文字列は、以下のようにすべて大文字にする必要があります。

   var input = document.getElementById('userInput').value.toUpperCase();
    switch (input) {
       case 'ALCOA':
               // do something
               break;
    }

toLowerCase() を使用する場合、switch(input) 関数内のケース文字列は、以下のようにすべて小文字にする必要があります。

 var input = document.getElementById('userInput').value.toLowerCase();
switch (input) {
   case 'alcoa':
           // do something
           break;
}
于 2013-01-07T18:34:02.403 に答える