regex - How can I remove "\n" not followed by another "\n" in javascript -
i want remove "\n" not followed "\n".
i have sample text here. want when press button, want remove "\n" not followed "\n" text below in textarea html tag.
abcdefg hijklmn opqrstu vwxyz 12345 67890 abcde zzzzz so, result expect this. removes "\n"s not followed "\n".
abcdefg hijklmnopqrstuvwxyz 1234567890abcde zzzzz but result this.
abcdefghijklmnopqrstuvwxyz1234567890abcde zzzzz this javascript code , html code have now.
html
<!doctype html> <html> <head> <meta charset="utf-8"> <script src="remove-line-breaks.js" type="text/javascript" charset="utf-8"></script> </head> <body> <h1>remove-line-breaks</h1> <h2>before</h2> <textarea id="original-textarea" cols="30" rows="15"> abcdefg hijklmn opqrstu vwxyz 12345 67890 abcde zzzzz </textarea> <br /> <input id ="modify-text-btn" type="submit" value="change" /> <h2>after</h2> <textarea id="modified-textarea" cols="30" rows="15"></textarea> </body> </html> javascript
window.onload = function(){ var modifytextbtn = document.getelementbyid("modify-text-btn"); modifytextbtn.addeventlistener("click", modifytext, false); var originaltextarea = document.getelementbyid("original-textarea"); var modifiedtextarea = document.getelementbyid("modified-textarea"); function modifytext(){ var pattern = new regexp("[^\\n](\\n)[^\\n]"); var newstr = originaltextarea.value; while (pattern.test(newstr)) { newstr = newstr.replace(pattern.exec(newstr)[1], ""); } modifiedtextarea.value = newstr; } } could please me solve problem?
more or less, you're doing lot more processing need to. change modifytext function this:
function modifytext(){ var pattern = new regexp("([^\\n])\\n([^\\n])", "g"); modifiedtextarea.value = originaltextarea.value.replace(pattern, "$1$2"); } the first change in definition of pattern . . . you' notice @ end, added , "g" in new regexp constructor. makes pattern global, meaning that, when it's applied, affect instances of pattern
once set up, have call replace once against field value , assign target field value.
update: sorry chopping off characters. :d i've updated both regex , replacement pattern.
the regex captures characters around line break , then, in replacement, puts them in, without line break in between them.
Comments
Post a Comment