2

我想删除新行周围的任何空格,从

Here is a new line. /n 
New line.

Here is a new line./n
New line.

我找到了各种示例如何删除空格以及如何删除新行,但没有找到如何用简单的 /n 替换 ' '+/n 的示例。我尝试了以下方法,但没有奏效:

paragraphs = paragraphs.replace(/(\r\n|\n|\r|' '+\n|' '+\r|\n+' '|\r+' ')/gm,'<br>'); 

更新:

这就是我解决它的方法:paragraphs = paragraphs.replace(/\r\n|\n|\r/gm,'\n'); // 清除空元素数组(双新行)paragraphs = $.grep(paragraphs,function(n){ return(n) }); // 清除 (p=0;p) 的所有双空格的文本

4

6 回答 6

2

我没有看到问题,以下不起作用吗?

var paragraph = "my paragraph with a space at the end \nand a new line";
paragraph.replace(/ \n/, "\n");

// or with multiple spaces, this is working too:
paragraph = "my paragraph with lot of spaces    \nzzzzz".replace(/ +\n/, "\n");

// or, for the more complete regex you want 
paragraphs = paragraphs.replace(/ [ \r\n]+/gm, "\n");
于 2013-10-30T23:21:27.173 回答
0
paragraphs = paragraphs.replace(/\ +\n/g,'\n');
于 2013-10-30T23:23:23.160 回答
0

您使用的正则表达式/(\r\n|\n|\r|' '+\n|' '+\r|\n+' '|\r+' ')/gm 没有按照您的意图进行;该'+ 部分匹配 1+ 个'字符;要匹配单个空格字符,只需键入空格(不带撇号),你应该这样写(如果我错了,请纠正我):/\r\n|\s+\n|\s+\r|\n+|\r+/g并像这样使用它:p.replace(/\r\n|\s+\n|\s+\r|\n+|\r+/g,"\n<br>"),或者试试这个功能:

//
var ws_nls_ws_2_nl =
( function ( sc, ws_nls_ws_rgx, str_trim_rgx, nl ) {
  return function ( input_txt ) {
    // split on "\n+" surounded by blanks
    // join with "\n"
    // trim the result string
    return sc( input_txt ).split( ws_nls_ws_rgx ).join( nl ).replace( str_trim_rgx, "" );
  };
} )(

  // get global String ctor
  ( function () { return String; } )(),

  // new line(s) with blanks around it, global
  /[\s\uFEFF\xA0]+(?:\n+|(?:\r\n)+|\r+)[\s\uFEFF\xA0]+/g,

  // str-trim reg, 
  // blanks at start or end
  /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

  "\n"

);
//
//  ws_nls_ws_2_nl("        Here is a new line.  \n   New line.   ");
//
//
于 2013-10-30T23:51:04.863 回答
0
于 2013-10-30T23:35:58.963 回答
0

可能您可以将字符串拆分为 \n 并应用 jQuery.trim()

于 2013-10-30T23:18:46.970 回答
0

好吧,这就是我最终清理输入文本字段的方式:

function cleanText(){
//aligns all new lines and splits text into single paragraphs
paragraphs = input.replace(/\r\n|\n|\r/gm,'\n');
paragraphs = paragraphs.split('\n');
// clears array of empty elements (double new lines)
paragraphs = $.grep(paragraphs,function(n){ return(n) });
// clears text of all double whitespaces
for (p=0;p<paragraphs.length; p++){
    paragraphs[p] = paragraphs[p].replace(/\s+/g, ' ');
    paragraphs[p] = $.trim(paragraphs[p]);
}
// joins everything to one string
var cleanedText = paragraphs.join("\n ") ;
// gets an array of single words
wordsArray=cleanedText.split(' ');
}
于 2013-11-04T22:46:46.480 回答