替换子字符串javascript

替换子字符串javascript,javascript,regex,ecmascript-6,replace,substring,Javascript,Regex,Ecmascript 6,Replace,Substring,我需要替换匹配正则表达式的字符串中的子字符串 const text = "There are many variations of passages of Lorem Ipsum available, <a href='https://stackoverflow.com/'>stackoverflow</a> but the majority have suffered alteration in some form, by injected humor, or ra

我需要替换匹配正则表达式的字符串中的子字符串

const text = "There are many variations of passages of Lorem Ipsum available,

<a href='https://stackoverflow.com/'>stackoverflow</a>

but the majority have suffered alteration in some form, by injected humor, or randomized words which 

<a href="/page2">page 2</a>

don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.
All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the";
我需要为所有外部超链接添加一个目标空白

const text = "There are many variations of passages of Lorem Ipsum available,

<a target='_blank' href='https://stackoverflow.com/'>stackoverflow</a>

but the majority have suffered alteration in some form, by injected humor, or randomized words which 

<a href="/page2">page 2</a>

don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of the text.
All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the";

您可以将此HTML添加到元素中,然后在所有链接上设置属性,而不是使用正则表达式:

常量文本='…'; const div=document.createElement'div'; div.innerHTML=文本; […div.queryselectoral'a[href]'].forEacha=>a.setAttribute'target','u blank'; const result=div.innerHTML;
结果常量中有空白HTML。

这里有很多问题

JavaScript字符串不能有换行符,模板文本可以稍后查看 一种引号中的Javascript字符串需要相同类型的转义引号,即这是不可能的,但这是\可能的\ 您不想在HTML上使用正则表达式 在这里,我获取所有以http开头的链接并设置目标

我假设您没有像a href=http\u is\u a\u protocol.html这样的链接 如果您可能有,那么您需要使用更聪明的选择器或查看我的第二个版本

//在这里,我使用一个模板文本倒勾来包含换行符和引号 const text=` Lorem Ipsum的段落有很多变体, 但大多数人都经历了某种形式的改变,通过注入幽默,或随意使用 看起来连一点都不可信。 如果你要使用LROM乱数假文,你需要确保在文本中间没有任何隐藏的尴尬。 互联网上所有的Lorem Ipsum生成器都倾向于在必要时重复预定义的块,这使得它成为`; const div=document.createElementdiv div.innerHTML=文本; […div.querySelectorAlla[href^=http].forEachfunctionlink{ link.target=\u blank;//或link.setAttributetarget,\u blank document.body.appendChilddiv;
}我需要将此文本中的所有外部超链接转换为……转换为什么?我编辑了这个问题,StackOverflowTackOverflowMaybe:查看我的更新以获取处理本地链接的完整URL的版本您现在已更改页面中的所有链接我假设OP将能够自定义选择器,因为我不确定对他来说什么是外部的。他代码中有一个外部和一个内部,示例中只有一个空白。那么,你的答案也是错误的,因为链接以http开头并不意味着它是外部的。这很可能是正确的。如果不是,那么他可以修改第二个版本。为什么如此防御?我会非常感兴趣为什么这会被否决