你可以如何在JavaScript中删除仅以特定字符开头的行的换行符?

huangapple go评论62阅读模式
英文:

How can I remove line breaks from lines that only start with a specific character in JavaScript?

问题

我尝试移除一个字符串中以特定字符开头的换行符,但找不到解决方案。在我的情况下,我尝试移除所有以引号开始的换行符。以下是一个示例:

输入:

`
Test
"How" +
"Can" +
"I" +
Do This?
`;

期望的结果:

`
Test "How" + "Can" + "I"
Do This?
`;

我只能找到一种方法来移除所有的换行符,但仍然无法找到只在满足条件时移除它们的解决方案。

英文:

I am trying to remove line breaks from a string that only begin with a specific character and am having trouble finding a solution. In my scenario I'm am trying to remove all line breaks where the line starts with a quotation mark. Heres an example:

Input:

`
Test
"How" +
"Can" +
"I" +
Do This?
`;

Desired Result:

`
Test "How" + "Can" + "I"
Do This?
`;

I've only been able to find a way to remove all line breaks. Still unable to find a solution to only remove them if a conditional is met.

答案1

得分: 3

以下是翻译好的部分:

你可以直接匹配引号,甚至不需要正则表达式:

let s = `
Test
"How" +
"Can" +
"I" +
Do This?
`;

s = s.replaceAll('\n"', ' "');
console.log(s);

在你的问题中,你还删除了每个新行字符前的 +。如果这是有意的,并且所有这样的 + 都应该被删除,那么可以这样做:

let s = `
Test
"How" +
"Can" +
"I" +
Do This?
`;

s = s.replaceAll('\n"', ' "').replaceAll(" +\n", "\n");
console.log(s);
英文:

You can just match the quote as well -- there's even no need for a regex:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let s = `
Test
&quot;How&quot; +
&quot;Can&quot; +
&quot;I&quot; +
Do This?
`;

s = s.replaceAll(&#39;\n&quot;&#39;, &#39; &quot;&#39;);
console.log(s);

<!-- end snippet -->

In your question you have also removed + before a new line character. If that was intended, and all such + should be removed, then:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let s = `
Test
&quot;How&quot; +
&quot;Can&quot; +
&quot;I&quot; +
Do This?
`;

s = s.replaceAll(&#39;\n&quot;&#39;, &#39; &quot;&#39;).replaceAll(&quot; +\n&quot;, &quot;\n&quot;);
console.log(s);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月24日 04:51:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定