javascript - 检查字符串是否以前缀开头

标签 javascript arrays string if-statement prefix

我想用 javascript 检查数组项是否以单词“prefix”开头。

到目前为止,我已经做了这样的事情:

let array = ["prefix-word1", "prefix-word2"];

array.forEach(function(element) {
      if (element.lastIndexOf('prefix', 0) == 0) {
        console.log('prefix');
      }
    }

由于某种原因,我不断收到前缀未定义的错误。请帮忙。

最佳答案

这个有效(检查代码注释):

let array = ["prefix-word1", "prefix-word2" , "does not start with prefix"];

array.forEach(function(element) {
   // Check if the first word is prefix
   if (element.indexOf('prefix') == 0) {
     console.log('prefix');
     console.log(element);
   }
});
 
 console.log("Second approach which is not suggested");
 array.forEach(function(element) {
   // not the correct approach as suggested by @Barmar though it works
   if (element.lastIndexOf('prefix',0) == 0) {
     console.log('prefix');
     console.log(element);
   }
});

关于javascript - 检查字符串是否以前缀开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53093241/

相关文章:

javascript - 单击展开,单击外部折叠

javascript - 在 jQuery 中启动 .hover 后,如何检查鼠标是否仍在悬停?

javascript - 如何通过ajax发送js数组?

c - 在 C 上避免此错误的正确方法是什么

string - clojure 删除字符串中模式的最后一个入口

python Pandas : Find a value in another dataframe and replace it

javascript - 在里面加载带有javascript的部分html

javascript - ionicPopup 完成加载后运行代码/事件?

c - 将字符串文件读取到字符串数组

python - 将 Pandas 数据帧的行映射到 numpy 数组