如何使用JavaScript移除链接URL开头的多余&quote;实体字符
清理URL开头多余"实体字符的JavaScript解决方案
需求说明
我需要移除URL开头的"实体字符,例如当链接的href属性取值为""https://www.google.com"时,需要通过JavaScript清理开头的多余引号实体。
初始尝试方案
最开始写的代码只能匹配特定前缀的链接,场景覆盖不全面:
$(document).ready(function(){ // 仅匹配href前缀为"https://的链接 $('a[href^=""https://"]').each(function(){ var oldUrl = $(this).attr("href"); // 获取当前链接地址 var newUrl = oldUrl.replace(""https://", "https://"); // 替换前缀生成新地址 $(this).attr("href", newUrl); // 写入新的href值 }); }); // 存在问题的链接示例 <a href=""https://www.google.com">Google</a> <a href=""https://www.gmail.com">Gmail</a>
最终可用方案
调整为遍历所有a标签,直接替换href属性中的转义引号字符,兼容更多场景:
$(document).ready(function(){ $("a").each(function() { // 可打开下方注释调试查看原始href值 //console.log($(this).attr("href")); var oldUrl = $(this).attr("href"); // 获取当前链接地址 var newUrl = oldUrl.replace('\\"', ''); // 替换多余的转义引号 // 可打开下方注释调试查看替换后的值 //console.log(newUrl); $(this).attr("href", newUrl); // 写入新的href值 }); });
内容的提问来源于stack exchange,提问作者Abhinav Banerjee
相关产品推荐
相关产品推荐

