如何为段落中无http/https的URL补全协议前缀?
前端JavaScript实现
用正则匹配<a>标签里的href属性值,跳过已有http/https协议的URL,给剩下的补全https://。
代码示例:
function addHttpsToLinks(htmlContent) { // 匹配双引号包裹的href,排除已有协议的URL return htmlContent.replace(/<a href="(?!https?:\/\/)([^"]+)"/g, '<a href="https://$1"'); } // 测试用例 const original = '<p>Testing if urls work <a href="google.com" rel="noopener noreferrer" target="_blank">google.com</a>google.com</p> this is some more content that might be added to the url <a href="www.google.com">www.Google.com</a> with some more text that follows. '; const processed = addHttpsToLinks(original); console.log(processed);
如果编辑器输出的是单引号包裹的href,可以把正则调整为:
htmlContent.replace(/<a href='(?!https?:\/\/)([^']+)'/g, "<a href='https://$1'");
要同时支持单双引号的话,用这个正则:
htmlContent.replace(/(<a href=['"])(?!https?:\/\/)([^'"]+)(['"])/g, '$1https://$2$3');
后端Python实现
利用Python的re模块做正则替换,逻辑和前端一致。
代码示例:
import re def add_https_to_links(html_content): # 替换双引号包裹的无协议href return re.sub(r'<a href="(?!https?:\/\/)([^"]+)"', r'<a href="https://\1"', html_content) # 测试用例 original = '<p>Testing if urls work <a href="google.com" rel="noopener noreferrer" target="_blank">google.com</a>google.com</p> this is some more content that might be added to the url <a href="www.google.com">www.Google.com</a> with some more text that follows. ' processed = add_https_to_links(original) print(processed)
支持单双引号的版本:
re.sub(r'(<a href=['"])(?!https?:\/\/)([^'"]+)(['"])', r'\1https://\2\3', html_content)
注意事项
- 上述正则只会处理
<a>标签的href属性,不会修改文本中直接出现的无协议URL(比如示例里的google.com文本),如果需要处理文本中的URL,需要另外写正则匹配。 - 如果要兼容ftp等其他协议,可以修改负向预查规则,比如
(?!https?:\/\/|ftp:\/\/),但如果只需要补全https,保持原规则即可。
内容的提问来源于stack exchange,提问作者bstory
相关产品推荐
相关产品推荐

