Refinance now before rates go up! Get multiple rate quotes at GetMyLender.com.

Remove or Replace Line Breaks using JavaScript

In web applications, whenever we add any textarea tag on the form to get some text from user. In textarea, user can write on new lines but while accessing that text if we don’t want such line breaks. Hence in this post, we will see how to remove line breaks from regular text using some simple javascript code.

Many times we simply think ki it is just a simple line break we don’t need to take care so much. But Line breaks in text are generally represented in three ways according to types of operating system.

1) \r\n => created on Windows OS
2) \n => created on Linux OS
3) \r => created on MAC OS

In order to remove line breaks from text we must deal with all three types of line breaks as typically your text could come from any of those sources.

Here we have given one simple line of javascript to replace multiple white spaces with single spaces so everything's a little cleaner looking.

Javascript provides one of the predefined function

 replace(regexp/substr, newstring);

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring.

Suppose we have form and that contain textarea to get product description, so we will get that description and remove all line breaks in following way :

 var vDescription = document.getElementById("txtDesc").value;
 vDescription = vDescription.replace(/(\r\n|\n|\r)/gm,"");

Here, "g" stands for "greedy" which means the replacement should happen more than once if possible. "m" stands for "many lines" means the replacement should take place over many lines "gm" at the end of the regex statement signifies that the replacement should take place over many lines (m) and that it should happen more than once (g). This regular expression tells it to replace all instance of the \r\n then replace all \n than finally replace all \r. It goes through and removes all types of line breaks from the designated text string.

Removing Extra Spaces from Lines

In above example Double line spaces may appear when we just want a single space. To remove all extra white spaces, just use this javascript code after the line break removal code:

     //Replace all double white spaces with single spaces
     vDescription = vDescription.replace(/\s+/g," ");

This javascript regex finds multiple whitespaces and replaces them with a single white space.


Conclusion :

I hope that this article would have helped you in understanding Regular expressions and methods to Remove or Replace Line Breaks using JavaScript. Your feedback and constructive contributions are always welcome.


No comments:

Post a Comment