代码之家  ›  专栏  ›  技术社区  ›  Olical

检查JavaScript中的变量是否为字符串

  •  1408
  • Olical  · 技术社区  · 15 年前

    19 回复  |  直到 8 年前
        1
  •  1573
  •   WD40    7 年前

    你可以用 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"
    

    this webpage . (不过,这个例子稍作修改)。

    对于使用 new String() ,但这很少使用,建议不要使用 [1] [二] . 如果你愿意的话,看看其他的答案如何处理这些问题。


    1. Google JavaScript风格指南 says to never use primitive object wrappers
    2. 道格拉斯·克罗克福德 recommended that primitive object wrappers be deprecated .
        2
  •  1825
  •   Mark Amery Harley Holcombe    9 年前

    这就是我的工作:

    if (typeof myVar === 'string' || myVar instanceof String)
    // it's a string
    else
    // it's something else
    
        3
  •  144
  •   Jonathan H    8 年前

    function isString(x) {
      return Object.prototype.toString.call(x) === "[object String]"
    }
    

    或者,内联(对此我有一个UltiSnip设置):

    Object.prototype.toString.call(myVar) === "[object String]"
    

    typeof new String("string") 是 object

    DRAX的答案是准确和实用的,应该是正确的答案(因为Pablo Santa Cruz绝对是错误的,我不会反对全民投票)

    lodash / underscore ).

    我最初的回答(很明显,这句话是对的)是:

    我是从underline.js转码的:

    ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach( 
        function(name) { 
            window['is' + name] = function(obj) {
                  return toString.call(obj) == '[object ' + name + ']';
        }; 
    });
    


    在Node.js中,这可以实现为一个模块:

    module.exports = [
      'Arguments', 
      'Function', 
      'String', 
      'Number', 
      'Date', 
      'RegExp'
    ].reduce( (obj, name) => {
      obj[ 'is' + name ] = x => toString.call(x) == '[object ' + name + ']';
      return obj;
    }, {});
    
        4
  •  80
  •   Jason Parker    11 年前

    我建议使用 jQuery公司 或

    两个函数都将处理DRAX提到的情况。。。也就是说,他们 二者都

    lodash/下划线.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
    

    lodash Documentation for _.isString() 更多细节。

    jQuery Documentation for $.type() 更多细节。

        5
  •  33
  •   Preview 2pha    10 年前
    function isString (obj) {
      return (Object.prototype.toString.call(obj) === '[object String]');
    }
    

    我在这里看到:

    http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/

        6
  •  27
  •   Cody    9 年前

    最佳方式:

    var s = 'String';
    var a = [1,2,3];
    var o = {key: 'val'};
    
    (s.constructor === String) && console.log('its a string');
    (a.constructor === Array) && console.log('its an array');
    (o.constructor === Object) && console.log('its an object');
    (o.constructor === Number || s.constructor === Boolean) && console.log('this won\'t run');
    

    另外,鸭子打字: 如果它看起来像鸭子,走起来像鸭子,闻起来像鸭子,那么它一定是一个数组 意思是,检查它的属性。

    希望这有帮助。

    记住,你也可以使用方法的组合。下面是一个使用 内联映射 类型 :

    var type = { 'number': Math.sqrt.bind(Math), ... }[ typeof datum ];
    

    下面是一个更“真实”的使用内联映射的示例:

    function is(datum) {
        var isnt = !{ null: true, undefined: true, '': true, false: false, 0: false }[ datum ];
        return !isnt;
    }
    console.log( is(0), is(false), is(undefined), ... );  // >> true true false
    

    null &安培; 0 !

    很多次 . 另一种避免键入的方法是组合Duck类型集:

    this.id = "998";  // use a number or a string-equivalent
    function get(id) {
        if (!id || !id.toString) return;
        if (id.toString() === this.id.toString()) http( id || +this.id );
        // if (+id === +this.id) ...;
    }
    

    两者 Number.prototype 和 String.prototype .toString() method . 您只需确保与数字等价的字符串是相同的,然后确保将其传递到 http 作为 Number 照顾 它的类型是什么。

    希望能给你更多的合作机会:)

        7
  •  17
  •   customcommander    7 年前

    我真的不明白为什么一个人不 typeof

    if (typeof str === 'string') {
      return 42;
    }
    

    是的,对于对象包装的字符串(例如。 new String('foo') (如果你看到了,就把它修好!)

    这个 Object.prototype.toString 诀窍是所有的前端开发人员在他们的职业生涯中有一天会被判有罪,但不要让它用它的聪明来愚弄你:只要有猴子修补对象原型,它就会崩溃:

    const isString = thing => Object.prototype.toString.call(thing) === '[object String]';
    
    console.log(isString('foo'));
    
    Object.prototype.toString = () => 42;
    
    console.log(isString('foo'));
        8
  •  13
  •   ScottyG    8 年前

    var myString = "test";
    if(myString.constructor === String)
    {
         //It's a string
    }
    
        9
  •  11
  •   Paul Rooney    7 年前

    这就是为什么性能很重要的一个很好的例子:

    例如,如果我想编写一个函数来测试某个东西是否是字符串,我可以通过以下两种方法之一来完成:

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

    2个) const isString = str => ((typeof str === 'string') || (str instanceof String));

    这两个都是非常直接的,那么什么可能影响性能呢?一般来说,函数调用会很昂贵,特别是如果你不知道内部发生了什么。在第一个例子中,有一个函数调用对象的toString方法。在第二个示例中,没有函数调用,因为typeof和instanceof是运算符。运算符明显快于函数调用。

    参见测试: https://jsperf.com/isstringtype

        10
  •  8
  •   Benj Sicam    11 年前

    function isString(val) {
       return typeof val === 'string' || ((!!val && typeof val === 'object') && Object.prototype.toString.call(val) === '[object String]');
    }
    
    console.log(isString('hello world!')); // true
    console.log(isString(new String('hello world'))); // true
    
        11
  •  7
  •   whmkr    6 年前
    if (s && typeof s.valueOf() === "string") {
      // s is a string
    }
    

    适用于两个字符串文本 let s = 'blah' let s = new String('blah')

        12
  •  4
  •   David    9 年前

    如果您在node.js环境中工作,那么只需在utils中使用内置函数isString。

    const util = require('util');
    if (util.isString(myVar)) {}
    

    编辑:正如@Jehy提到的,这是从v4开始就被弃用的。

        13
  •  4
  •   Erez Cohen    7 年前

    我认为,@customcommander解决方案应该能满足您90%的案例:

    typeof str === 'string'
    

    new String('something') 在你的代码中)。

    如果你有兴趣处理 String 对象(例如,您希望从第三方获得一些var),然后使用lodash作为@ClearCloud8建议的方法似乎是一个清晰、简单和优雅的解决方案。

    不过,我建议谨慎使用lodash等图书馆,因为它们的规模。而不是做

    import _ from 'lodash'
    ...
    _.isString(myVar)
    

    它带来了整个巨大的洛达斯物体,我建议如下:

    import { isString as _isString } from 'lodash'
    ...
    _isString(myVar)
    

    使用简单的绑定应该没问题(这里我指的是客户机代码)。

        14
  •  3
  •   Chris Dolphin    13 年前

    我还发现这个方法也很好,而且比其他例子要短得多。

    if (myVar === myVar + '') {
       //its string
    } else {
       //its something else
    }
    

    通过连接空引号,它将值转换为字符串。如果 myVar

        15
  •  3
  •   Yin    10 年前
    var a = new String('')
    var b = ''
    var c = []
    
    function isString(x) {
      return x !== null && x !== undefined && x.constructor === String
    }
    
    console.log(isString(a))
    console.log(isString(b))
    console.log(isString(c))
    
        16
  •  3
  •   Grant Miller    7 年前

    以下方法将检查是否有任何变量是字符串( 包括不存在的变量 ).

    const is_string = value => {
      try {
        return typeof value() === 'string';
      } catch (error) {
        return false;
      }
    };
    
    let example = 'Hello, world!';
    
    console.log(is_string(() => example)); // true
    console.log(is_string(() => variable_doesnt_exist)); // false
    
        17
  •  3
  •   Mulan    7 年前

    字符串

    String(x) === x // true, if x is a string
                    // false in every other case
    

    const test = x =>
      console.assert
        ( String(x) === x
        , `not a string: ${x}`
        )
    
    test("some string")
    test(123)           // assertion failed
    test(0)             // assertion failed
    test(/some regex/)  // assertion failed
    test([ 5, 6 ])      // assertion failed
    test({ a: 1 })      // assertion failed
    test(x => x + 1)    // assertion failed

    同样的技术也适用于 数字

    Number(x) === x // true, if x is a number
                    // false in every other case
    

    const test = x =>
      console.assert
        ( Number(x) === x
        , `not a number: ${x}`
        )
    
    test("some string") // assertion failed
    test(123)           
    test(0)             
    test(/some regex/)  // assertion failed
    test([ 5, 6 ])      // assertion failed
    test({ a: 1 })      // assertion failed
    test(x => x + 1)    // assertion failed

    为了 正则表达式

    RegExp(x) === x // true, if x is a regexp
                    // false in every other case
    

    const test = x =>
      console.assert
        ( RegExp(x) === x
        , `not a regexp: ${x}`
        )
    
    test("some string") // assertion failed
    test(123)           // assertion failed
    test(0)             // assertion failed
    test(/some regex/)  
    test([ 5, 6 ])      // assertion failed
    test({ a: 1 })      // assertion failed
    test(x => x + 1)    // assertion failed

    同样适用于 对象 -

    Object(x) === x // true, if x is an object
                    // false in every other case
    

    const test = x =>
      console.assert
        ( Object(x) === x
        , `not an object: ${x}`
        )
    
    test("some string") // assertion failed
    test(123)           // assertion failed
    test(0)             // assertion failed
    test(/some regex/)  
    test([ 5, 6 ])      
    test({ a: 1 })      
    test(x => x + 1)    

    但是,检查一下 阵列

    Array.isArray(x) === x // true, if x is an array
                           // false in every other case
    

    const test = x =>
      console.assert
        ( Array.isArray(x)
        , `not an array: ${x}`
        )
    
    test("some string") // assertion failed
    test(123)           // assertion failed
    test(0)             // assertion failed
    test(/some regex/)  // assertion failed
    test([ 5, 6 ])      
    test({ a: 1 })      // assertion failed
    test(x => x + 1)    // assertion failed

    这种技术确实 不 功能 然而-

    Function(x) === x // always false
    
        18
  •  1
  •   Community Mohan Dere    9 年前

    只是为了扩展@DRAX的 answer

    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 s和 undefined 类型,它将处理非字符串类型,例如 0

        19
  •  1
  •   Tomozma    7 年前

    这对我来说已经足够了。

    警告: 看我帖子的底部。

    Object.prototype.isString = function() { return false; };
    String.prototype.isString = function() { return true; };
    
    var isString = function(a) {
      return (a !== null) && (a !== undefined) && a.isString();
    };
    

    你可以像下面这样使用这个。

    //return false
    isString(null);
    isString(void 0);
    isString(-123);
    isString(0);
    isString(true);
    isString(false);
    isString([]);
    isString({});
    isString(function() {});
    isString(0/0);
    
    //return true
    isString("");
    isString(new String("ABC"));
    

    这在以下情况下不正确:

    //this is not a string
    var obj = {
        //but returns true lol
        isString: function(){ return true; }
    }
    
    isString(obj) //should be false, but true
    
        20
  •  1
  •   Noris    7 年前

    一个简单的解决方案是:

    var x = "hello"
    
    if(x === x.toString()){
    // it's a string 
    }else{
    // it isn't
    }
    
        21
  •  1
  •   yaya    7 年前

    Typechecker助手:

    function isFromType(variable, type){
      if (typeof type == 'string') res = (typeof variable == type.toLowerCase())
      else res = (variable.constructor == type)
      return res
    }
    

    用法:

    isFromType('cs', 'string') //true
    isFromType('cs', String) //true
    isFromType(['cs'], Array) //true
    isFromType(['cs'], 'object') //false
    

    另外,如果希望它是递归的(如数组是一个对象),可以使用 instanceof .

    ['cs'] instanceof Object //true )

        22
  •  0
  •   Hashbrown    6 年前

    我将在这里转到另一个路径,它试图判断变量是特定类型的,还是特定类型集的成员。

    是 7 一根绳子?那为什么 /\d/.test(7) 工作?
    {toString:()=>('hello there')} 一根绳子?那为什么 ({toString:()=>('hello there')}) + '\ngeneral kenobi!'
    这些不是关于 应该

    所以我做了一个 duckyString() function
    下面我将测试许多没有其他答案的案例。对于每个代码:

    • 对它和实际字符串运行相同的字符串操作以比较输出(证明它们可以被视为字符串)
    • 将字符串like转换为真实字符串以显示 使期望实际字符串的代码的输入正常化
    text = 'hello there';
    out(text.replace(/e/g, 'E') + ' ' + 'hello there'.replace(/e/g, 'E'));
    out('Is string? ' + duckyString(text) + '\t"' + duckyString(text, true) + '"\n');
    
    text = new String('oh my');
    out(text.toUpperCase() + ' ' + 'oh my'.toUpperCase());
    out('Is string? ' + duckyString(text) + '\t"' + duckyString(text, true) + '"\n');
    
    text = 368;
    out((text + ' is a big number') + ' ' + ('368' + ' is a big number'));
    out('Is string? ' + duckyString(text) + '\t"' + duckyString(text, true) + '"\n');
    
    text = ['\uD83D', '\uDE07'];
    out(text[1].charCodeAt(0) + ' ' + '😇'[1].charCodeAt(0));
    out('Is string? ' + duckyString(text) + '\t"' + duckyString(text, true) + '"\n');
    
    function Text() { this.math = 7; }; Text.prototype = {toString:function() { return this.math + 3 + ''; }}
    text = new Text();
    out(String.prototype.match.call(text, '0') + ' ' + text.toString().match('0'));
    out('Is string? ' + duckyString(text) + '\t"' + duckyString(text, true) + '"\n');
    

    这和 !!x 与 x===true 喜欢
    jQuery对象;它们是数组吗?不,它们够好吗?是的,你可以让他们通过 Array.prototype 功能很好。
    对于 字符串使代码的互操作性降低。

    hEllo thErE hEllo thErE
    Is string? true "hello there"
    
    OH MY OH MY
    Is string? true "oh my"
    
    368 is a big number 368 is a big number
    Is string? true "368"
    
    56839 56839
    Is string? true "😇"
    
    0 0
    Is string? true "10"
    

    所以,一切都是关于 为什么?
    如果,像我一样,你从谷歌来到这里,想看看 弦状 ,这是一个答案。

    这是因为它都是if语句,没有函数调用像 .toString() .
    toString() 的或多字节字符,在这种情况下,除了生成字符串和分别计算字节所组成的字符外,没有其他检查方法

    function duckyString(string, normalise, unacceptable) {
        var type = null;
        if (!unacceptable)
            unacceptable = {};
        if (string && !unacceptable.chars && unacceptable.to == null)
            unacceptable.to = string.toString == Array.prototype.toString;
    
        if (string == null)
            ;
    
        //tests if `string` just is a string
        else if (
            !unacceptable.is &&
            (typeof string == 'string' || string instanceof String)
        )
            type = 'is';
    
        //tests if `string + ''` or `/./.test(string)` is valid
        else if (
            !unacceptable.to &&
            string.toString && typeof string.toString == 'function' && string.toString != Object.prototype.toString
        )
            type = 'to';
    
        //tests if `[...string]` is valid
        else if (
            !unacceptable.chars &&
            (string.length > 0 || string.length == 0)
        ) {
            type = 'chars';
            //for each char
            for (var index = 0; type && index < string.length; ++index) {
                var char = string[index];
    
                //efficiently get its length
                var length = ((duckyString(char, false, {to:true})) ?
                    char :
                    duckyString(char, true) || {}
                ).length;
    
                if (length == 1)
                    continue;
    
                //unicode surrogate-pair support
                char = duckyString(char, true);
                length = String.prototype[Symbol && Symbol.iterator];
                if (!(length = length && length.call(char)) || length.next().done || !length.next().done)
                    type = null;
            }
        }
    
        //return true or false if they dont want to auto-convert to real string
        if (!(type && normalise))
            //return truthy or falsy with <type>/null if they want why it's true
            return (normalise == null) ? type != null : type;
    
        //perform conversion
        switch (type) {
        case 'is':
            return string;
        case 'to':
            return string.toString();
        case 'chars':
            return Array.from(string).join('');
        }
    }
    

    包括以下选项

    • 询问哪个方法认为它是string-y
    • 排除字符串检测方法(如不喜欢 )

    out('Edge-case testing')
    function test(text, options) {
        var result = duckyString(text, false, options);
        text = duckyString(text, true, options);
        out(result + ' ' + ((result) ? '"' + text + '"' : text));
    }
    test('');
    test(null);
    test(undefined);
    test(0);
    test({length:0});
    test({'0':'!', length:'1'});
    test({});
    test(window);
    test(false);
    test(['hi']);
    test(['\uD83D\uDE07']);
    test([['1'], 2, new String(3)]);
    test([['1'], 2, new String(3)], {chars:true});
    
    • 所有的阴性病例似乎都有原因
    • 在支持字符串迭代器的浏览器上支持多字节的Char数组

    输出:

    Edge-case testing
    is ""
    null null
    null null
    to "0"
    chars ""
    chars "!"
    null null
    chars ""
    to "false"
    null null
    chars "😇"
    chars "123"
    to "1,2,3"
    
        23
  •  -2
  •   Aryeh Beitz Shubham Sharma    9 年前

    我不确定你是不是想知道 string 不管它的内容是什么,或者它的内容是数字还是字符串,不管它的类型是什么。


    但要根据它的内容知道它是一个字符串还是一个数字,我会使用这个:

    function isNumber(item) {
        return (parseInt(item) + '') === item;
    }
    

    例如:

    isNumber(123);   //true
    isNumber('123'); //true
    isNumber('123a');//false
    isNumber('');    //false
    
        24
  •  -2
  •   Pato    7 年前

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

    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