简体   繁体   中英

Check string contains substring in javascript

I'm building a node application and a module of this application checks whether the nameservers of a given domain name point to AWS.

Using the dns module I have the below code:

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

hostnames outputs an array of hostnames and the specific domain I've used has the following hostname structure (x4):

ns-xx.awsdns-xx.xxx

But console.log(hostnames.indexOf('awsdns') > -1); returns false ?

If hostnames is an array, then hostnames.indexOf('awsdns') is looking for an entry that exactly matches (entire string) 'awsdns' .

To look for substrings in the array, use some :

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

Or with ES6 syntax:

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

Live Example:

 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> 

try

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

Since hostnames is an array, you need to check index of an actual hostname, not the array.

Note that this only works because you've said that if any of the entries has the substring, they all will. (Which is extremely unusual.) Otherwise, it would fail if the first entry didn't but a subsequent one did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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