如何在JavaScript中检查字符串是否包含数字? [英] How to check if a string contains a number in JavaScript?

查看:53
本文介绍了如何在JavaScript中检查字符串是否包含数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不难从JavaScript中的其他字符串中辨别出包含数字的字符串.

I don't get how hard it is to discern a string containing a number from other strings in JavaScript.

Number('')的计算结果为 0 ,而''绝对不是人类的数字.

Number('') evaluates to 0, while '' is definitely not a number for humans.

parseFloat 强制使用数字,但允许数字以任意文本结尾.

parseFloat enforces numbers, but allow them to be tailed by abitrary text.

isNaN 的计算结果为false.

isNaN evaluates to false for whitespace strings.

那么根据简单而合理的定义,检查字符串是否为数字的编程功能是什么?

So what is the programatically function for checking if a string is a number according to a simple and sane definition what a number is?

推荐答案

通过使用以下功能,我们可以测试javascript字符串是否包含数字.在上面的函数中,使用t代替t,我们需要将javascript字符串作为参数传递,然后该函数将返回true或false

By using below function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javascript string as a parameter, then the function will return either true or false

function hasNumbers(t)
{
var regex = /\d/g;
return regex.test(t);
}    

这篇关于如何在JavaScript中检查字符串是否包含数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆