我需要我的网站在Google地图上显示地址并链接到同一地址。
CMS正在输出格式化文本,因此它在页面上看起来很好(带有段落和中断标记),但我需要在href中将它们删除,以便正确链接。
换句话说,我输出的是这样的东西:
<p>Address Line 1<br>
Address line 2<br>
City, State, Zip</p>
但我需要一个围绕此文本的链接,该链接使用CMS的相同输出,但从中删除HTML标记。所以,像这样:
<a href="http://maps.google.com/?q=Address Line 1, Address Line 2 City, State, Zip"</a>
我已经能够剥离标签并用空格替换它们,但它也会从链接中的格式化文本中剥离它们。我无法仅剥离链接中的标签而不是格式化文本。
有人有想法吗?
答案 0 :(得分:2)
你试过$()。text()和encodeURIComponent吗?
$('.Result').html(encodeURIComponent($('.req').text()))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="req"><span>abc,<span>eef</span></span></div>
<div class="Result"></div>
答案 1 :(得分:2)
是的,我认为这是你的第二行,你在那里进行替换......在那一点上,地址&#39;只是一个文本字符串,所以你真的想在它上面使用普通的旧javascript正则表达式:
var strippedAddress = address.replace(/[\r\n]{1,2}/g, ' ');
那应该这样做!
希望这有帮助!
答案 2 :(得分:1)
你可以用replace():
来做<强> HTML:强>
<p id="address">Address Line 1<br>
Address line 2<br>
City, State, Zip</p>
<a id="gMapLink" href="http://maps.google.com/?q=Address Line 1, Address Line 2 City, State, Zip"</a>
<强> JS:强>
$(document).ready(function () {
var address = $('#address').html(),
link = 'http://maps.google.com/?q=',
addressStripped = address.replace(/<br>/g, ',');
$('#gMapLink').prop('href', link + addressStripped);
console.log(addressStripped, $('a').prop('href'))
});
参见JSFiddle here。
答案 3 :(得分:0)
我假设您在jquery中表示您的标签,因此我认为这是How to strip HTML tags with jQuery?的重复
...如果你真的想用逗号替换你的换行符,你可以为\ n字符替换字符串,这是换行符的字符
答案 4 :(得分:0)
之前有人问过,我刚刚搜索了一下谷歌搜索'javascript从字符串中删除html标签'并找到了多种方式(大部分都在stackOverflow上...)
您可以尝试以下方法:
var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
textContent和innerText做的相似,但不一样。我会研究它们,找到最适合你的那个。