删除文本,使用JavaScript在字符串中跟随注释标记的空格 - 在字符串中创建新行

问题描述 投票:1回答:1

我正在努力解决this CodeWars挑战:

完成解决方案,以便它删除传入的任何一组注释标记之后的所有文本。行末尾的任何空格也应该被删除。

给定一个输入字符串:

apples, pears # and bananas
grapes
bananas !apples

预期的输出将是:

apples, pears
grapes
bananas

到目前为止,我已经尝试过:

function solution(input, markers) {

  let string = input.split();
  let newString = " ";

  for (let i = 0; i < string.length; i++) {

    let words = string[i];
    //console.log(words);

    if (words.includes(markers || "/n")) {
      //go to the next line and keep building newString
    }
    newString += words;
  }
  return newString.toString();
}

这是返回apples,pears#andbananas/ngrapes/nbananas!apples,因为你可以看到,我不知道如何在其中一个标记出现时,或者当/n存在时在字符串中创建一个新行。

我试过了

if (words.includes(markers || "/n")) {
  //go to the next line and keep building newString
  newString += "\n";
}

if (words.includes(markers || "/n")) {
  //go to the next line and keep building newString
  words + "\n";
}

但这些都没有任何效果。

javascript arrays string newline markers
1个回答
4
投票

具有编码挑战的站点通常具有级别(如CodeWars)。在这种情况下,我建议用更容易的水平坚持一点,直到你真正流利地解决它们。

还要检查其他人提交的解决方案:可以从中学到很多东西。

我之所以这么说是因为你的代码中存在很多错误,看起来你可以从更简单的层次中获益更多,而不仅仅是在这里抓住解决方案并发布它。

您对代码的一些评论:

  • 你用空格初始化你的newString。这是一个错误的开始。那个空间不保证在那里。您应该只从输入中获取字符。它应该是一个空字符串。
  • 换行符不是"/n",而是"\n"
  • input.split()将字符串转换为字符数组。如果您的目标是通过索引来访问字符,那么您也可以使用字符串来实现:input[i]为您提供该偏移处的字符。
  • 变量名称很重要。命名变量string不是很有帮助。 words也不是,实际上它只有一个角色。所以character将是一个更好的选择。
  • includes期望一个字符串作为参数,但你通过markers|| "/n"没有额外的价值,因为markers是一个真正的值,所以||将在那里停止(短路评估)。由于markers是一个数组而不是字符串,因此includes将该值转换为逗号分隔的字符串。显然,输入中不太可能出现字符串。您需要单独测试每个标记字符,并检查换行符。
  • 你的if声明的正文是空的(在你的主要尝试中)。这没有用。也许你正在寻找continue;,它将跳过循环的其余部分并继续下一次迭代。
  • 没有规定可以跳过标记字符后面的字符。
  • 您没有规定消除标记字符之前出现的间距。
  • newString是一个字符串,所以没有必要调用newString.toString();

试着坚持你的想法,这是你的代码纠正:

function solution(input, markers) {
  let newString = "";
  for (let i = 0; i < input.length; i++) {
    let character = input[i];
    if (markers.includes(character)) {
        // move i to just before the end of the current line
        i = input.indexOf("\n", i)-1;
        // Remove the white space that we already added at the end
        newString = newString.trimRight();
        // If no newline character at end of last line: break
        if (i < 0) break;
        // Skip rest of this iteration
        continue;
    }
    newString += input[i];    
  }
  return newString;
}

但是有更简单的方法可以做到这一点。例如,首先将输入拆分为行。

这是我发布的解决方案:

const solution = (input, markers) =>
    input.split("\n").map(line => 
        markers.reduce((line, marker) => 
            line.split(marker, 1)[0].trimRight(), line)).join("\n");  
© www.soinside.com 2019 - 2024. All rights reserved.