简体   繁体   中英

How check if a string is substring with indexof [JAVASCRIPT]

I have a method:

function isSubString(word,array){}

This method, given an array of words and a word, tries if the word is a substring of the others words in array.

for(var i=0;i<array.length;i++){

        if(JSON.stringify(array[i]).indexOf(JSON.stringify(word))>0){
            return 1;
        }
    }
    return 0;

For example array=['home','dog'] and word='ho' ;

Word ho is sub string of home but this method is wrong. Anyone can help me?

You don't need JSON.stringify() , use String.prototype.indexOf()

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex . Returns -1 if the value is not found.

if(array[i].indexOf(word) >-1 ){

Using array.some()

 function isSubstring(word, array) { return array.some(function(el){return el.indexOf(word) != -1}) } var array = ['home','dog'] var word = 'ho' var isSub = isSubstring(word, array) // Demo output document.write(isSub) 

if you want all elements to match the substring use array.every() instead

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