2011-07-12 217 views
4

如何通过jquery检查字符串是否包含任何数值?jQuery - 检查字符串是否包含数字值

我搜索了很多例子,但我只是想方法来检查一个数字,而不是一个字符串中的数字。我试图找到像$(this).attr('id').contains("number");

(P/S:我的DOM ID会像Large_a(不含数值),Large_a_1(与数值),Large_a_2等)

何种方法均应我用?

+0

一个第一谷歌搜索结果: http://stackoverflow.com/questions/3955345/javascript-jquery-get-字符数字 –

回答

3

此代码检测由下划线符号开头结尾数字(azerty1_2将匹配 “2”,但azerty1将不匹配):

if (matches = this.id.match(/_(\d)+$/)) 
{ 
    alert(matches[1]); 
} 
+0

不需要分组,* test *可能更合适(* match *返回匹配数组,* test *只是测试)。所以'if(/_\d+$/.test(this.id)){...}'。很好地注意到OP可能只希望追踪数字。 :-) – RobG

+0

对不起,我只是喜欢短代码...我们永远不知道数字的价值是否需要:-) –

+0

完成它:if(ui.draggable.children()。attr('id ').match(/ _(\ d +)$ /)!= null) – shennyL

7

你可以使用正则表达式:

var matches = this.id.match(/\d+/g); 
if (matches != null) { 
    // the id attribute contains a digit 
    var number = matches[0]; 
} 
2

简易版:

function hasNumber(s) { 
    return /\d/.test(s); 
} 

更高效的版本(保持在一个闭合正则表达式):

var hasNumber = (function() { 
    var re = /\d/; 
    return function(s) { 
     return re.test(s); 
    } 
}()); 
+0

我很好奇你的关闭版本是多少效率?我认为闭包的开销是值得的,以避免每次重新创建正则表达式? – nnnnnn

相关问题