简体   繁体   English

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

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

I'm trying to solve this CodeWars challenge: 我正在尝试解决此CodeWars挑战:

Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. 完成解决方案,以使它去除所有传入的注释标记后面的所有文本。该行末尾的任何空格也应被去除。

Given an input string of: 给定一个输入字符串:

 apples, pears # and bananas grapes bananas !apples 

The output expected would be: 预期的输出将是:

 apples, pears grapes bananas 

So far I've tried: 到目前为止,我已经尝试过:

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

And this is returning apples,pears#andbananas/ngrapes/nbananas!apples because, as you can see, I don't know how to create a new line in the string when one of the markers is present, or when /n is present. 这将返回apples,pears#andbananas/ngrapes/nbananas!apples因为如您所见,当存在一个标记或存在/n时,我不知道如何在字符串中创建新行。

I've tried 我试过了

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

and

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

but neither of these are having any effect. 但这些都不起作用。

Sites that have coding challenges often have levels (like CodeWars). 遇到编码挑战的站点通常具有级别(例如CodeWars)。 In this case I would suggest to stick a bit longer with the easier levels until you are really fluent in solving them. 在这种情况下,我建议您在较简单的级别上坚持更长的时间,直到您真正熟练地解决它们为止。

Also check the solutions that others have submitted: a lot can be learned from that. 还要检查其他人提交的解决方案:可以从中学到很多。

I say this because there are so many things wrong in your code, that it seems you will benefit more from covering easier levels a bit longer, than from just grabbing a solution here and posting it. 我之所以这样说,是因为您的代码中存在很多错误,似乎与更长久地涵盖更简单的级别相比,您将从中获得更多好处,而不仅仅是从此处获取并发布解决方案。

Some comments on your code: 关于您的代码的一些注释:

  • You initialise your newString with a space. 您用空格初始化newString That is a wrong start. 那是一个错误的开始。 That space is not warranted to be there. 该空间不保证在那里存在。 You should only take characters from the input. 您只能从输入中获取字符。 It should be an empty string. 它应该是一个空字符串。
  • The newline character is not "/n" , but "\\n" 换行符不是"/n" ,而是"\\n"
  • input.split() converts a string to an array of characters. input.split()将字符串转换为字符数组。 If your aim was to make it possible to access characters through indexing, then realise that you can do so with a string as well: input[i] gives you the character at that offset. 如果您的目标是使通过索引访问字符成为可能,请意识到您也可以使用字符串进行input[i]input[i]为您提供该偏移量处的字符。
  • Variable names are important. 变量名称很重要。 Naming a variable string is not very helpful. 命名可变string不是很有帮助。 Nor is words , when actually it holds one character. words也不是,实际上它只有一个字符。 So character would be a better choice. 所以character会是一个更好的选择。
  • includes expects a string as argument, but you pass markers . includes期望将字符串作为参数,但是您传递了markers The || "/n" || "/n" || "/n" has no additional value, because markers is a truthy value and so || || "/n"没有附加值,因为markers是真实值,所以|| will stop right there (short-circuit evaluation). 将在此处停止(短路评估)。 And as markers is an array, not a string, includes converts that value into a comma-separated string. 并且由于markers是一个数组,而不是字符串, includes将值转换为逗号分隔的字符串。 Obviously that string is very unlikely to occur in your input. 显然,该字符串不太可能在您的输入中出现。 You need to test for each marker character individually, and also check for the newline character. 您需要分别测试每个标记字符,并检查换行符。
  • The body of your if statement is empty (in your main attempt). if语句的主体为空(主要尝试中)。 This cannot be useful. 这没有用。 Maybe you were looking for continue; 也许您正在寻找continue; which will skip the rest of the loop and continue with the next iteration of it. 这将跳过循环的其余部分,并继续进行下一次迭代。
  • There is no provision to skip the characters that follow a marker character. 没有规定跳过后面标记字符的字符。
  • You have no provision to eliminate spacing that occurs before a marker character. 您没有提供消除标记字符前出现间距的措施。
  • newString is a string, so there is no need to call newString.toString(); newString是一个字符串,因此无需调用newString.toString();

Trying to stay with your idea, here is your code corrected: 尝试保持您的想法,这是您的代码已更正:

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

But there are easier ways to do this. 但是有更简单的方法可以做到这一点。 For instance, by splitting your input into lines first. 例如,首先将输入分成几行。

Here is the solution I posted: 这是我发布的解决方案:

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