我想从
中删除新行周围的任何空格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>');
更新:
这就是我如何解决它: paragraph = paragraphs.replace(/ \ r \ n | \ n | \ r \ n / gm,'\ n'); //清除空元素数组(双新行) paragraph = $ .grep(paragraph,function(n){return(n)}); //清除所有双空格的文本 for(p = 0; p
答案 0 :(得分: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");
答案 1 :(得分:0)
可能是你可以用\ n分割字符串并应用jQuery.trim()
答案 2 :(得分:0)
paragraphs = paragraphs.replace(/\ +\n/g,'\n');
答案 3 :(得分:0)
试试这个:
HTML:
<div id="myDiv">
Here is a new line. /n
New line.
</div>
javaScript:
//get the innerHTML
var paragraph = document.getElementById("myDiv").innerHTML;
//extract the part that you want to replace using RegExp.exec() method
var newPart = /[ ]*\/n/.exec(paragraph);
//simply replace the new part with what you want
paragraph = paragraph.replace(newPart, '/n');
alert(paragraph);
答案 4 :(得分:0)
您使用的RegExp,/(\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. ");
//
//
答案 5 :(得分: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(' ');
}