我的正则表达式效果很好,除了我想添加 url 必须包含http://
或https://
的要求,而我修复正则表达式的尝试破坏了它。任何帮助不胜感激!
let rx = new RegExp(/((([A-Za-z]{3,9}:(?://)?)(?:[-;:&=+$,w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,w]+@)[A-Za-z0-9.-]+)((?:/[+~%/.w-_]*)???(?:[-+=&;%@.w_]*)#?(?:[.!/\w]*))?)/g);
let replaced = text.replace(
rx,
`<a href="$1" target="_blank">$1</a>`
);
将[A-Za-z]{3,9}:(?://)?
替换为https?://
。由于您没有使用任何变量来构建正则表达式,因此请使用正则表达式文本而不是构造函数表示法。
/bhttps?://(?:(?:[-;:&=+$,w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,w]+@)[A-Za-z0-9.-]+)(?:/[+~%/.w_-]*??(?:[-+=&;%@.w_]*)#?[.!/\w]*)?/g
查看在线正则表达式演示
bhttps?://
,匹配https://
或http://
作为一个整体,将适用于(?:(?:[-;:&=+$,w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,w]+@)[A-Za-z0-9.-]+)
、(?:[-;:&=+$,w]+@)?[A-Za-z0-9.-]+
和(?:www.|[-;:&=+$,w]+@)[A-Za-z0-9.-]+
中的两种替代词,因此也需要在www.
之前使用协议。
还有许多冗余的捕获组,请考虑删除不需要的组,并将需要量化的组转换为非捕获组。
let text = "https://example.com http://example.com/more?k=v ftp://not.this.one www.example www.example.com";
let rx = /bhttps?://(?:(?:[-;:&=+$,w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,w]+@)[A-Za-z0-9.-]+)(?:/[+~%/.w_-]*??(?:[-+=&;%@.w_]*)#?[.!/\w]*)?/g;
let replaced = text.replace(rx,'<a href="$&" target="_blank">$&</a>');
console.log(replaced);
$&
反向引用是指整个正则表达式匹配值,无需用一对额外的捕获括号包装整个模式。