Javascript、string、RegEx、if和else if、console.log不同的输出

Javascript, string, RegEx, if and else if, console.log different output

本文关键字:if 输出 log else string RegEx Javascript console      更新时间:2023-09-26

我想按顺序输出字符串的元音,所以我决定使用RegEx来完成。

但是,当我把表达式放在(if和else-if)中的不同位置时,同一个表达式的输出是不同的。有人能解释一下吗?

function ordered_vowel_word(str) {
  if(str.match(/[aeiou]{1,}/g) !== ""){
  var arr = str.match(/[aeiou]{1,}/g);
      console.log(arr);
  }
  else
      console.log(str);
  }
ordered_vowel_word("bcg");
ordered_vowel_word("eebbscao");

/*输出*/

ordered_vowel_word("bcg");

===>空

ordered_vowel_word("eebbscao");

===>["ee","ao"]

但如果我重组表达式,

function ordered_vowel_word(str) {
  if(str.match(/[^aeiou]/) !== "")
      console.log(str); 
  else if(str.match(/[aeiou]{1,}/g) !== ""){
  var arr = str.match(/[aeiou]{1,}/g);
      console.log(arr); 
  }
}

输出将是

ordered_vowel_word("bcg");

===>bgv

ordered_vowel_word("eebbscao");

===>eebbscao

请注意,如果至少有一个匹配,string.match将返回数组,如果没有匹配,则返回null

我想你想要的是:

if(str.match(/[aeiou]{1,}/g) == null){ // no matches

if(str.match(/[aeiou]{1,}/g) != null){ //has a match

至于排序,您必须用str.match处理您得到的数组。

请查看此SO答案以对数组进行排序。可以,可以对字符使用><运算符。

str.match的返回值(使用它的方式)是一个数组,其中包含匹配时的匹配项。此外,当没有匹配项时,它不是空字符串。。。它实际上是空的。

尝试将你在if条件下测试的内容更改为:

str.match(/[aeiou]{1,}/g) !== null)