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 <br />
line breaks to send the query like this:
var query = $('#textarea-src').val();
var query = encodeURIComponent(query);
var query = query.replace(/\n\r?/g, '<br />'); // replace new lines with line brea开发者_开发技巧ks
Then I make the call to Google:
$.ajax({
url: apiUrl,
dataType: 'jsonp',
success: function(data) {
var response = data.data.translations[0].translatedText;
var response = response.replace(/ <br \/> ?/g, '\n'); // replace line breaks with new lines
$('#textarea-trg').val(response);
}
});
The problem is that Google's responses have whitespace around the line breaks.
When I query "hello<br />world"
the response in French is "bonjour \u003cbr /\u003e monde"
With my replace(/ <br \/> ?/g, '\n')
regex I can correct for that but when I query two line breaks after each other "hello<br /><br />world"
the response is "bonjour \u003cbr /\u003e\u003cbr /\u003e monde"
How can I correct for this?
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.
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
精彩评论