我使用的是 jQuery 1.11。
我有一个在 html 中显示的字符串,我希望将相同的字符串复制并粘贴到文本区域。
对我来说问题是要粘贴的字符串包含换行符 <br />
。为了正确显示文本区域中的字符串,我必须替换换行符 <br />
换行 \n
.
我正在使用replace
,但我编写的每个排列都是为了替换 <br />
与 \n
失败。该字符串沿一行打印。
我已经搜索了谷歌等,但这对我不起作用 - 我在这里缺少一些基本的东西。
如何编写字符串替换函数来替换 <br />
与 \n
?
这是我的字符串:
[employer]<br />[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)<br /><br />
这是对我不起作用的替换代码:
var text = $(this).closest('.employment_history_suggestion_add_button').prev().text(); // Get text of the previous span element
text = text.replace(/<br\s*\/?>/mg,"\n"); // replace line break with new line for correct display in textarea.
编辑
这是现在可以运行的代码。
我正在使用.text()
- 应该一直使用.html()
.
我正在使用\\n
- 应该一直使用\n
.
var text = $(this).closest('.employment_history_suggestion_add_button').prev().html(); // Get html of the copied string (keep the line breaks for replacing with new lines).
text = text.replace(/<br\s*\/?>/gim, "\\n");
$('#id_employment_history_employerTA').val(function (i, oldVal) {
return oldVal + text; // append the value of text to the textarea.
});
我希望这对某人有帮助。
最佳答案
虽然您希望在替换模式中对 \n
回车符进行双重转义,但尚不清楚代码的哪一部分失败了:
var text = '[employer]<br />[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)<br /><br />'
text = text.replace(/<br\s*\/?>/gim, "\\n")
alert(text);
结果:
[employer]\n[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)\n\n
关于jQuery - 将换行符 <br/> 替换为新行\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34111842/