简体   繁体   English

为什么我的代码无法通过 Javascript 中的字符串删除空格测试?

[英]Why does my code fail to pass the test of removing spaces from string in Javascript?

Hi everyone.大家好。 I'm new to coding and I'm failing to pass this test: I need to write my code in order for this string:我是编码新手,但未能通过此测试:我需要为该字符串编写代码:

'<h2>         Lost In Space</h2>'

to be changed to this string (basically remove the extra spaces between the header and the text):改成这个字符串(基本上去掉header和文本之间多余的空格):

'<h2>Lost In Space</h2>'

The code I wrote looks like this and in my editor it seems to return the correct output but for some reason it fails when put through the online test我写的代码看起来像这样,在我的编辑器中它似乎返回了正确的 output 但由于某种原因它在通过在线测试时失败了

function markdownParser(markdown) {
    let arr = markdown.trim().split(' ');
    let firstItemInArray = arr[0]; 
    if(firstItemInArray[0] === '<') {
        arr.shift(); 
        let newString = arr.join(' '); 
        let trimmedString = newString.trim(); 
        return `${firstItemInArray}${trimmedString}`
      } else {
        return markdown;
    }
}

Any idea why this is happening and where is my mistake?知道为什么会发生这种情况以及我的错误在哪里吗?

Failing test: edge_cases测试失败:edge_cases

expected '<h2>         Lost In Space</h2>' to deeply equal '<h2>Lost In Space</h2>'

Kind of cheating and a bit of a hack, but a reliable one.有点作弊和一点黑客,但一个可靠的。 Could be changed to only trim the text nodes.可以更改为仅修剪文本节点。 Name implies it's Markdown, so this might not actually work?名称暗示它是 Markdown,所以这实际上可能不起作用?

 str=`<h2> test</h2>` const div = document.createElement('div') div.innerHTML=str div.querySelectorAll('*').forEach(x=>x.innerHTML=x.innerHTML.trim()) console.log(div.innerHTML)
 <div id="div"></div>

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

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