jQuery - 用新行替换换行符 <br /> \n

use*_*539 1 html jquery replace

我正在使用 jQuery 1.11。

我有一个以 html 显示的字符串,我希望将相同的字符串复制并粘贴到文本区域。

对我来说问题是要粘贴的字符串包含换行符<br />。为了在文本区域中正确显示字符串,我必须<br />用新行替换换行符\n

我正在使用replace,但我编写的用 替换 的每个排列<br />都会失败\n。该字符串沿一行打印。

我已经搜索了谷歌等,但这对我不起作用 - 我在这里缺少一些基本的东西。

如何编写字符串替换函数来替换<br />with \n

这是我的字符串:

[employer]<br />[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)<br /><br />
Run Code Online (Sandbox Code Playgroud)

这是对我不起作用的替换代码:

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.
Run Code Online (Sandbox Code Playgroud)

编辑

这是现在有效的代码。

我正在使用.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.
});
Run Code Online (Sandbox Code Playgroud)

我希望这对某人有帮助。

l'L*_*L'l 5

尽管您希望\n在替换模式中双重转义回车符,但尚不清楚代码的哪一部分失败了:

var text = '[employer]<br />[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)<br /><br />'

text = text.replace(/<br\s*\/?>/gim, "\\n")
alert(text);
Run Code Online (Sandbox Code Playgroud)

结果:

[employer]\n[mm/yyy] - [mm/yyy] - ([number] years1, [number] months)\n\n
Run Code Online (Sandbox Code Playgroud)