如何确定变量是字符串还是JavaScript中的其他变量?


当前回答

从lodash库v4.0.0实现

// getTag.js

const toString = Object.prototype.toString;

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function getTag(value) {
    if (value == null) {
        return value === undefined 
            ? "[object Undefined]" 
            : "[object Null]";
    }
    return toString.call(value);
}
// isString.js

import getTag from "./getTag.js";

/**
 * Checks if `value` is classified as a `String` primitive or object.
 *
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
 * @example
 *
 * isString('abc')
 * // => true
 *
 * isString(1)
 * // => false
 */
function isString(value) {
    const type = typeof value;
    return (
        type === "string" || (type === "object" &&
                              value != null &&
                              !Array.isArray(value) &&
                              getTag(value) == "[object String]")
    );
}

export default isString;

其他回答

为了扩展@DRAX的答案,我会这样做:

function isWhitespaceEmptyString(str)
{
    //RETURN:
    //      = 'true' if 'str' is empty string, null, undefined, or consists of white-spaces only
    return str ? !(/\S/.test(str)) : (str === "" || str === null || str === undefined);
}

它还将考虑null和未定义的类型,并将处理非字符串类型,例如0。

只有字符串而没有数字的代码

isNaN("A") = true;
parseInt("A") = NaN;
isNaN(NaN) = true;

然后我们可以使用isNaN(parseInt())来只包含字符串

let ignoreNumbers=“ad123a4m”;让ign=ignoreNumbers.split(“”).map((ele)=>isNaN(parseInt(ele))?ele:“”).加入(“”);console.log(ign);

您可以使用typeof运算符:

var booleanValue = true; 
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"

此网页中的示例。(尽管对示例进行了轻微修改)。

在使用new String()创建字符串的情况下,这不会像预期的那样工作,但这很少被使用,并且建议对[1][2]使用。如果您愿意,请查看其他答案以了解如何处理这些问题。


谷歌JavaScript风格指南说,永远不要使用原始对象包装器。Douglas Crockford建议弃用基本对象包装器。

我建议使用jQuery或lodash/Undercore中的内置函数。它们更易于使用和阅读。

任何一个函数都将处理上述DRAX的情况。。。也就是说,它们都检查(A)变量是字符串文本还是(B)它是string对象的实例。在这两种情况下,这些函数都将值正确地标识为字符串。

lodash/Undercore.js

if(_.isString(myVar))
   //it's a string
else
   //it's something else

jQuery

if($.type(myVar) === "string")
   //it's a string
else
   //it's something else

有关详细信息,请参阅_.isString()的lodash文档。

有关详细信息,请参阅$.type()的jQuery文档。

您可以使用此函数确定任何对象的类型:

var type = function(obj) {
    return Object.prototype.toString.apply(obj).replace(/\[object (.+)\]/i, '$1').toLowerCase();
};

要检查变量是否为字符串,请执行以下操作:

type('my string') === 'string' //true
type(new String('my string')) === 'string' //true
type(`my string`) === 'string' //true
type(12345) === 'string' //false
type({}) === 'string' // false

https://codepen.io/patodiblasi/pen/NQXPwY?editors=0012

要检查其他类型:

type(null) //null
type(undefined) //undefined
type([]) //array
type({}) //object
type(function() {}) //function
type(123) //number
type(new Number(123)) //number
type(/some_regex/) //regexp
type(Symbol("foo")) //symbol