英文:
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
"How" +
"Can" +
"I" +
Do This?
`;
s = s.replaceAll('\n"', ' "');
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
"How" +
"Can" +
"I" +
Do This?
`;
s = s.replaceAll('\n"', ' "').replaceAll(" +\n", "\n");
console.log(s);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论