繁体   English   中英

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

[英]Remove Text, White Space That Follows Comment Marker in String With JavaScript - Create New Line In String

我正在尝试解决此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";
}

但这些都不起作用。

遇到编码挑战的站点通常具有级别(例如CodeWars)。 在这种情况下,我建议您在较简单的级别上坚持更长的时间,直到您真正熟练地解决它们为止。

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

我之所以这样说,是因为您的代码中存在很多错误,似乎与更长久地涵盖更简单的级别相比,您将从中获得更多好处,而不仅仅是从此处获取并发布解决方案。

关于您的代码的一些注释:

  • 您用空格初始化newString 那是一个错误的开始。 该空间不保证在那里存在。 您只能从输入中获取字符。 它应该是一个空字符串。
  • 换行符不是"/n" ,而是"\\n"
  • input.split()将字符串转换为字符数组。 如果您的目标是使通过索引访问字符成为可能,请意识到您也可以使用字符串进行input[i]input[i]为您提供该偏移量处的字符。
  • 变量名称很重要。 命名可变string不是很有帮助。 words也不是,实际上它只有一个字符。 所以character会是一个更好的选择。
  • includes期望将字符串作为参数,但是您传递了markers || "/n" || "/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");  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM