繁体   English   中英

检查字符串是否包含JavaScript中的子字符串

[英]Check string contains substring in javascript

我正在构建节点应用程序,并且此应用程序的模块检查给定域名的名称服务器是否指向AWS。

使用dns模块,我有以下代码:

dns.resolveNs(domain, function (err, hostnames) {
    console.log(hostnames);
    console.log(hostnames.indexOf('awsdns') > -1);
});

hostnames输出一组主机名,并且我使用的特定域具有以下主机名结构(x4):

ns-xx.awsdns-xx.xxx

但是console.log(hostnames.indexOf('awsdns') > -1); 返回false

如果hostnames是一个数组,则hostnames.indexOf('awsdns')会寻找'awsdns'完全匹配的条目(整个字符串)。

要在数组中查找子字符串,请使用some

console.log(hostnames.some(function(name) {
    return name.indexOf('awsdns') > -1;
});

或使用ES6语法:

console.log(hostnames.some((name) => name.indexOf('awsdns') > -1));

现场示例:

 var a = ['12.foo.12', '21.bar.21', '42.foo.42']; // Fails there's no string that entirely matches 'bar': snippet.log(a.indexOf('bar') > -1); // Works, looks for substrings: snippet.log(a.some(function(name) { return name.indexOf('bar') > -1; })); 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

尝试

hostnames[0].indexOf('awsdns') > -1;

由于主机名是一个数组,因此您需要检查实际主机名的索引,而不是数组。

请注意,这仅行之有效,因为您已经说过,如果任何条目都具有子字符串,它们都将起作用。 (这是非常不寻常的。)否则,如果第一个条目没有,而后一个条目没有,它将失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM