javascript - 如何检查字符串是否是带有indexof的子字符串[JAVASCRIPT]

标签 javascript arrays

我有一个方法:

function isSubString(word,array){}

给定一个单词数组和一个单词,此方法会尝试该单词是否是数组中其他单词的子字符串。

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

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

例如array=['home','dog']word='ho'

Word hohome 的子字符串,但这种方法是错误的。有人可以帮助我吗?

最佳答案

您不需要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. Returns -1 if the value is not found.

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

关于javascript - 如何检查字符串是否是带有indexof的子字符串[JAVASCRIPT],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34658163/

相关文章:

java - 砖 block 位置,在打砖 block 游戏中,使用 Java 中的数组

javascript - YouTube 控制可访问性报告

javascript - 来自 PHP 的 echo-ed HTML 元素未在 JAVASCRIPT 中读取

javascript - 使用 puppeteer 单击可见元素

javascript - 网页中的文本字段和文本框显示在网页图像下方。图片应作为背景图片

java - 如何在android中解析这个Json数组

javascript - Jquery - 选择选项时填写输入文本

php - 如何保持收集的数据库行的顺序与传递给 where 子句的数组相同

javascript - 有条件地在新选项卡中打开网址

javascript - 在每次出现特定子字符串时剪切数组中存在的 JS 字符串并附加到同一数组