JavaScript:替换包含换行符的字符串

标签 javascript replace

引用号:JS fiddle

我有一个<pre>内部包含多行的元素。使用 JQuery,我正在调用 .html()获取innerHTML ,然后执行字符串 replace()在返回的 HTML 字符串上。但是,替换仅适用于第一行,其余行可能会失败,因为返回的 innerHTML有换行符。

您能否建议一种将两行都放在 <pre> 内的解决方法?更换了?

最佳答案

请注意有关在 replace 函数中使用 flags 参数的警告,该警告位于 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace :

Note: The flags argument is a non-standard Mozilla extension. A string specifying a combination of regular expression flags. The use of the flags parameter in the String.replace method is non-standard. Instead of using this parameter, use a RegExp object with the corresponding flags.

(强调的是我的)

因此,您应该使用正确的正则表达式,而不是使用这些参数:

string = string.replace(/&lt;your-login&gt;/g, userName);
string = string.replace(/&lt;repository-name&gt;/g, repoName);

关于JavaScript:替换包含换行符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26345242/

相关文章:

php - =?UTF-8?B??= 通过 php 邮件发送的电子邮件问题

javascript - 找到知道是否打印 php 页面的方法 -ctrl p - 并在 mysql 中更新

javascript - 尝试使用 javascript 停止图像加载

mysql - 替换 MySQL 查询中的文本?

javascript - 如何替换字符串中的 $1 , $2

javascript - 如何比较 JavaScript 中的事件

javascript - vue-google-maps - 如何设置 map 样式?

javascript - VSCode 搜索替换正则表达式

java - Java中替换字符串后的字符串长度?

regex - 从字符串中删除动态链接