简体   繁体   English

如何检查字符串是否是索引为[JAVASCRIPT]的子字符串

[英]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' ; 例如array=['home','dog']word='ho' ;

Word ho is sub string of home but this method is wrong. 单词hohome子字符串,但是此方法错误。 Anyone can help me? 有人可以帮助我吗?

You don't need JSON.stringify() , use String.prototype.indexOf() 您不需要JSON.stringify() ,使用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 . indexOf()方法返回第一次出现指定值的调用String对象内的索引,从fromIndex开始搜索。 Returns -1 if the value is not found. 如果找不到该值,则返回-1

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

Using array.some() 使用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 如果您希望所有元素都与子字符串匹配,请使用array.every()代替

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

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