Javascript正则表达式,使删除单段换行符

Javascript regex, make remove single paragraph line breaks

本文关键字:单段 换行符 删除 正则表达式 Javascript      更新时间:2023-09-26

我有以下格式的文本:

word word,
word word.
word word
word word.

这并不是两个单词的格式所特有的,它只是在这么多字符之前的一个换行符,而不是一个长长的段落字符串。但我正试图把它变成一长串的段落。所以它应该是这样的:

word word, word word.
word word word word.

如果我使用代码text.replace(/$'n(?=.)/gm, " ")并将其输出到终端,我会得到如下文本:

 word word, word word.
 word word word word.

它在段落开头有一个额外的空间,但这对于我想要做的事情来说已经足够了(尽管如果有一种方法可以在一个替换函数中删除它,那就太好了)。问题是,当我将其输出到文本区域时,它不会删除字符,而我只得到如下文本:

 word word,
 word word.
 word word
 word word.

我正在尝试在客户端完成这项工作,目前正在Firefox中运行。

我对regex不是最好的,所以这可能真的很简单,我只是不知道如何做。但任何帮助都将不胜感激。谢谢

回车是''r所以您需要使用

text.replace(/$('r|'n)(?=.)/gm, " ");

在满足您请求的一段代码下面,我也删除了前导空格(由空行引起),使用了带有替换函数的闭包:

var regex  = /([^.])'s+/g;
var input  = 'word word,'nword word.'n'nword word'nword word.';
var result = input.replace(regex, function(all, char) {
  return (char.match(/'s/)) ? char : char + ' ' ;
});
document.write('<b>INPUT</b> <xmp>' + input + '</xmp>');
document.write('<b>OUTPUT</b> <xmp>' + result + '</xmp>');

Regex突破

([^.])        # Select any char that is not a literal dot '.'
              # and save it in group $1
's+           # 1 or more whitespace char, remove trailing spaces (tabs too)
              # and all type of newlines ('r'n, 'r, 'n)

注意

如果出于某种原因,您希望保留前导空格,请简化以下代码:

var regex   = /([^.])'s+/g;
var replace = '$1 ';
var input   = 'word word,'nword word.'n'nword word'nword word.';
var result = input.replace(regex, replace);
document.write('<b>INPUT</b> <xmp>' + input + '</xmp>');
document.write('<b>OUTPUT</b> <xmp>' + result + '</xmp>');

您可能错过了一些''r,这里有一种方法可以匹配所有类型的新行,而不需要额外的空格:

var input = 'word word,'nword word.'n'nword word'nword word.';
            // split if 2 or more new lines
var out = input.split(/('r'n|'n|'r){2,}?/)
            // split the paragraph by new lines and join the lines by a space
            .map((v) => v.split(/'r'n|'n|'r/).join(' '))
            // there is some spaces hanging in the array, filter them
            .filter((v) => v.trim())
            // join together all paragraphs by 'n
            .join(''n');
$('#txt').append(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txt"></textarea>