我如何在JavaScript中区分一个字符串和另一个字符串?

时间:2015-02-23 16:22:34

标签: javascript uppercase

我在警报提示中键入了很多单词,例如:" USB"但我的错误是当我尝试与相同的字符串进行比较但小写时,如果我键入" usb"我怎样才能与" USB"并且发出了一个警告说,"字符串是相同的",我做同样的但是当第一个字母是大写的时候例如"你好"和#34;你好",但如果我的字符串完全是大写的,我怎么比较呢?

我试图这样做

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");

5 个答案:

答案 0 :(得分:0)

if(respuesta.toLowerCase() == textoALT.toLowerCase()) {
// do something

答案 1 :(得分:0)

给定两个字符串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
}

答案 2 :(得分:0)

你可以通过两种方式完成:

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
}

答案 3 :(得分:0)

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

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

用于一般目的。

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

这将返回true。

答案 4 :(得分:0)

if (a.toLowerCase() === b.toLowerCase()) {
    // strings match regardless of case
}

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

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