我在JavaScript中有一个字符串,它包含一个a标签href.我想删除所有链接和文本.我知道如何删除链接并保留内部文本,但我想完全删除链接.
例如:
var s = "check this out <a href='http://www.google.com'>Click me</a>. cool, huh?";
Run Code Online (Sandbox Code Playgroud)
我想使用正则表达式,所以我留下:
s = "check this out. cool, huh?";
Run Code Online (Sandbox Code Playgroud)
Chr*_*heD 17
这将去掉之间的一切<a和/a>:
mystr = "check this out <a href='http://www.google.com'>Click me</a>. cool, huh?";
alert(mystr.replace(/<a\b[^>]*>(.*?)<\/a>/i,""));
Run Code Online (Sandbox Code Playgroud)
这不是万无一失的,但也许它会为你的目的而做的伎俩......
小智 13
只是为了澄清,为了剥离链接标记并保持它们之间的所有内容不变,这是一个两步过程 - 删除开始标记,然后删除结束标记.
txt.replace(/<a\b[^>]*>/i,"").replace(/<\/a>/i, "");
Run Code Online (Sandbox Code Playgroud)
工作样本:
<script>
function stripLink(txt) {
return txt.replace(/<a\b[^>]*>/i,"").replace(/<\/a>/i, "");
}
</script>
<p id="strip">
<a href="#">
<em>Here's the text!</em>
</a>
</p>
<p>
<input value="Strip" type="button" onclick="alert(stripLink(document.getElementById('strip').innerHTML))">
</p>
Run Code Online (Sandbox Code Playgroud)