jquery如何检查字符串是否包含特定的数值

时间:2018-01-04 11:01:41

标签: jquery

如果字符串值包含指定的数值,如何检查jQuery? 例如;

a= 13
c = 12

b = 'we have 13 monkeys in the Zoo"

如何检查( a in b = True)(c in b = False)

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式实现:



var a = 13,
    c = 12,
    b = 'we have 13 monkeys in the Zoo';
    
if (b.match('\\b' + a + '\\b')) {
  console.log('b includes a');
}

if (b.match('\\b' + c + '\\b')) {
  console.log('b includes c');
}




使用\b限制搜索来匹配整个单词,在这里" 13",解决乔治指出的问题。

答案 1 :(得分:0)

您可以使用以下代码:

var s = $.grep(b.split(' '), function(v) {
  return v == a
});

if (s.length) {
  console.log('b includes a');
}

<强>演示

var a = 13,
  c = 12,
  b = 'we have 13 monkeys in the Zoo';
d = 'we have 134 monkeys in the Zoo';

var s = $.grep(b.split(' '), function(v) {
  return v == a
});

var t = $.grep(d.split(' '), function(v) {
  return v == a
});

if (s.length) {
  console.log('b includes a');
}
if (t.length) {
  console.log('d includes a');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

相关问题