简体   繁体   中英

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 breaks

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 \
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 \
\
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM