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

时间:2018-10-31 23:24:13

标签: javascript arrays string if-statement prefix

我想用javascript检查数组项是否以“前缀”开头。

到目前为止,我已经做了类似的事情:

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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);
   }
});

答案 1 :(得分:-2)

尝试在函数中使用双引号而不是像这样的“前缀”使用单引号。