Check if a single character is a whitespace?

后端 未结 9 1197
清酒与你
清酒与你 2021-02-06 21:21

What is the best way to check if a single character is a whitespace?

I know how to check this through a regex.

But I am not sure if this is the best way if I onl

9条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 21:58

    var testWhite = (x) {
        var white = new RegExp(/^\s$/);
        return white.test(x.charAt(0));
    };
    

    This small function will allow you to enter a string of variable length as an argument and it will report "true" if the first character is white space or "false" otherwise. You can easily put any character from a string into the function using the indexOf or charAt methods. Examples:

    var str = "Today I wish I were not in Afghanistan.";
    testWhite(str.charAt(9));  // This would test character "i" and would return false.
    testWhite(str.charAt(str.indexOf("I") + 1));  // This would return true.
    

提交回复
热议问题