正则表达式的JavaScript修饰行中断? [英] JavaScript trim line breaks with regex?
问题描述
我正在使用Google翻译翻译文本区域的内容,并使用API响应填充另一个文本区域.
在我的源文本区域中,我将/n
换行符替换为<br />
换行符,以发送如下查询:
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
然后我打电话给Google:
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);
}
});
问题在于Google的回复在换行符周围有空格.
当我查询"hello<br />world"
时,法语响应为"bonjour \u003cbr /\u003e monde"
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"
使用我的replace(/ <br \/> ?/g, '\n')
正则表达式,我可以对此进行更正,但是当我彼此查询两次换行符时"hello<br /><br />world"
,响应为"bonjour \u003cbr /\u003e\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"
我该如何纠正?
推荐答案
您可以使空格在两侧都是可选的:
You can make the spaces optional on both sides:
var response = response.replace(/ ?<br \/> ?/g, '\n');
另一个选择是使用/ *<br \/> */g
或/\s*<br \/>\s*/g
.
为清楚起见,让我们使用下划线而不是空格:
如果您的文本是"a_<br />_<br />_b"
,则/_<br \/>_?/g
失败,因为第一次匹配会占用第二个空格(导致"a\n<br />_b"
),并且第二个<br />
不能没有前导空格就匹配.
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.
这篇关于正则表达式的JavaScript修饰行中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!