【问题标题】:How can i difference between one and string and another one in JavaScript?我如何在 JavaScript 中区分一个字符串和另一个字符串?
【发布时间】:2015-04-25 01:03:34
【问题描述】:

我在警报提示中输入了很多单词,例如:“USB”,但我的错误是当我尝试与相同的字符串进行比较但小写时,如果我输入“usb”如何与“进行比较USB”并发送一个警报说,“字符串相同”,我做同样的事情,但是当第一个字母是大写时,例如“Hello”和“hello”,但是我如何比较我的字符串是否完全在大写?

我试过这样做

var res = document.getElementById("answer").value;
var resp = res.charAt(0).toUpperCase()+ res.slice(1);

if(respuesta == textoALT.charAt(0).toUpperCase()+ textoALT.slice(1))
alert("bla bla");

【问题讨论】:

  • 简单地将它们转换成相同的大小写。
  • 为什么要使用charAt?只需 toUpperCase() 或 toLowerCase() 将整个语句大写或小写。
  • 我认为您可能会将比较与分配混淆。您的 if 语句没有分配任何内容,因此您应该能够将两个字符串都转换为大写或小写并进行比较。您不需要 charAt(0) 等。

标签: javascript uppercase


【解决方案1】:
if (a.toLowerCase() === b.toLowerCase()) {
    // strings match regardless of case
}

请注意,您几乎应该始终使用“===”而不是“==”。 "===" 测试某个值和数据类型(数字、字符串、布尔值、对象等)是否与另一个匹配,而 "==" 仅测试值是否匹配(在执行类型转换之后)。例如:

if ("42" == 42) { // true
if ("42" === 42) { // false

【讨论】:

    【解决方案2】:

    这里不需要使用charAt。你可以使用 toUpperCase()

    var str = "USB";
    var str1 = "usb";
    alert((str==str1.toUpperCase()));
    

    一般用途。

    alert((str.toUpperCase()==str1.toUpperCase()));
    

    这将返回 true。

    【讨论】:

      【解决方案3】:

      您可以通过两种方式进行:

      a) 区分大小写

      if (a === b) {
        // the strings are the same text in the same case
      }
      

      记得使用===运算符,因为这意味着a和b是相同的类型和值。

      操作员== 将只比较值。

      b) 不区分大小写 - 检查两个值是否都给出

      if (
          (a && b) && // optionally to ensure both values are defined:)
          (a.toLowerCase() === b.toLowerCase())
         ) {
        // the strings are the same text but in a different case
      }
      

      【讨论】:

        【解决方案4】:

        给定两个字符串,ab

        if (a === b) {
          // the strings are the same text in the same case
        }
        if (a.toLowerCase() === b.toLowerCase()) {
          // the strings are the same text but in a different case
        }
        

        【讨论】:

          【解决方案5】:
          if(respuesta.toLowerCase() == textoALT.toLowerCase()) {
          // do something
          

          【讨论】:

          • 比较每个字符串的小写字母。
          • 最好解释一下你的代码做了什么以及为什么它可以解决用户问题,而不是仅仅停留在一行或两行代码中。它还有助于防止您的答案被系统标记为低质量,就像这个一样。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多