![](/img/trans.png)
[英]how to check if a string contains substring and color it in 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.