200

如何检查 var 是否是 JavaScript 中的字符串?

我试过这个,它不起作用......

var a_string = "Hello, I'm a string.";

if (a_string typeof 'string') {
    // this is a string
}
4

7 回答 7

430

你很接近:

if (typeof a_string === 'string') {
    // this is a string
}

在相关说明中:如果创建字符串,则上述检查将不起作用,new String('hello')因为类型将Object改为。有一些复杂的解决方案可以解决这个问题,但最好永远避免以这种方式创建字符串。

于 2011-06-08T23:43:13.747 回答
81

运算符不是中缀(因此您的示例中的typeofLHS 没有意义)。

你需要像这样使用它......

if (typeof a_string == 'string') {
    // This is a string.
}

记住,typeof是一个操作符,而不是一个函数。尽管如此,你会看到typeof(var)在野外被大量使用。这与var a = 4 + (1).

此外,您也可以使用==(相等比较运算符),因为两个操作数都是Strings(typeof 总是返回 a String),JavaScript 被定义为执行与我使用相同的步骤===(严格比较运算符)。

正如Box9 提到的,这不会检测到实例化的String对象。

你可以用......检测到。

var isString = str instanceof String;

js小提琴

...或者...

var isString = str.constructor == String;

js小提琴

但这在多环境中不起作用window(想想iframe)。

你可以解决这个问题...

var isString = Object.prototype.toString.call(str) == '[object String]';

js小提琴

但同样,(正如Box9 提到的那样),您最好只使用文字String格式,例如var str = 'I am a string';.

进一步阅读

于 2011-06-08T23:43:21.427 回答
15

结合前面的答案提供了这些解决方案:

if (typeof str == 'string' || str instanceof String)

或者

Object.prototype.toString.call(str) == '[object String]'
于 2014-02-06T14:42:27.730 回答
8

以下表达式返回true

'qwe'.constructor === String

以下表达式返回true

typeof 'qwe' === 'string'

以下表达式返回false(原文如此!):

typeof new String('qwe') === 'string'

以下表达式返回true

typeof new String('qwe').valueOf() === 'string'

最好和正确的方法(恕我直言):

if (someVariable.constructor === String) {
   ...
}
于 2018-07-16T21:33:32.343 回答
0

现在,我相信最好使用 typeof() 的函数形式,所以......

if(filename === undefined || typeof(filename) !== "string" || filename === "") {
   console.log("no filename aborted.");
   return;
}
于 2016-06-27T21:17:00.320 回答
0

在所有情况下检查 null 或 undefined a_string

if (a_string && typeof a_string === 'string') {
    // this is a string and it is not null or undefined.
}
于 2017-09-25T17:48:02.063 回答
-3

我个人的方法似乎适用于所有情况,它是测试是否存在所有仅存在于字符串的成员。

function isString(x) {
    return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}

见:http: //jsfiddle.net/x75uy0o6/

我想知道这种方法是否存在缺陷,但多年来它一直对我有用。

于 2015-03-31T17:00:03.667 回答