Skip to content Skip to sidebar Skip to footer

Javascript Trim Line Breaks With Regex?

I am using Google Translate to translate the contents of a textarea and fill another textarea with the API response. In my source textarea I am replacing the /n newlines with

Solution 1:

You can make the spaces optional on both sides:

var response = response.replace(/ ?<br \/> ?/g, '\n');

Another option is using / *<br \/> */g or /\s*<br \/>\s*/g.

For clarity, lets use underscores instead of spaces: If your text is "a_<br />_<br />_b", /_<br \/>_?/g fails because the first match consumes the second space (resulting in "a\n<br />_b"), and the second <br /> cannot be matched without a leading space.

Solution 2:

Try:

var query   = $('#textarea-src').val();
var query   = query.replace(/\n|\r/g, '<br\/>'); // replace new lines with line breaks

Or, if posible, firstly send request for translating into Google, then replace newlines|linefeeds with BR

Post a Comment for "Javascript Trim Line Breaks With Regex?"