简体   繁体   English

从 textarea 中删除换行符和分段符

[英]Remove line breaks and paragraph breaks from textarea

I am trying to 'flatten' (removing line breaks and paragraph breaks) from any given input from a textarea.我正在尝试从文本区域的任何给定输入中“展平”(删除换行符和分段符)。

Suppose the input is:假设输入是:

select * where { 
    ?s ?p ?o .
} limit 100 

The expected outcome is:预期结果是:

select * where { ?s ?p ?o . } limit 100 

So far I have managed to remove the line breaks using the following piece of code:到目前为止,我已经设法使用以下代码删除换行符:

val.replace(/$(\r|\n)(?=.)/gm, ' ');

Which is currently giving me:目前给我的是:

select * where {    ?s ?p ?o . } limit 100

Any thoughts?有什么想法吗? Thanks in advance!提前致谢!

I'd suggest我建议

val = val.replace(/[^\S\r\n]*[\r\n]+\s*/g, ' ')

This will "shrink" linebreaks (including any consecutive blank lines) with adjacent whitespaces into a single space char.这会将带有相邻空格的换行符(包括任何连续的空白行)“缩小”为单个空格字符。

Here,这里,

  • [^\S\r\n]* - matches 0+ horizontal spaces [^\S\r\n]* - 匹配 0+ 个水平空格
  • [\r\n]+ - 1+ CR or LF chars [\r\n]+ - 1+ CR 或 LF 字符
  • \s* - any 0+ whitespce chars. \s* - 任何 0+ whitespce 字符。

See the regex demo .请参阅正则表达式演示

About CRLF:关于 CRLF:
- As @Unimportant suggests, replace \s+ with space. - 正如@Unimportant 所建议的,将\s+替换为空格。
Reason is that formatting the result won't work anyway it's done.原因是格式化结果无论如何都不会起作用。
Better to be consistent with even looking separation.更好地与甚至看起来分离一致。

About Paragraph breaks and Breaks:关于段落分隔符和换行符:
- Would be replace </?p\s*>|<br\s*/> with nothing. - 将替换</?p\s*>|<br\s*/>什么都没有。

So, 2 separate regex run independent of each other would do the job.因此,两个独立的正则表达式彼此独立运行就可以完成这项工作。

Add the space character \s to your match criteria, and also add a * to signify that there can be more than one concurrent match.将空格字符\s添加到匹配条件中,并添加*表示可以有多个并发匹配。 From here you'll simply want to replace such characters with an empty string instead of a space.从这里您只需要将这些字符替换为空字符串而不是空格。

This can be seen in the following:这可以在下面看到:

 const val = `select * where {?s?p?o. } limit 100 `; console.log(val.replace(/$(\r|\n|\s)*(?=.)/gm, ''));

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

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