You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript正则表达式提取含ws、wss、http、https的URL?

JavaScript正则提取含WebSocket协议的URL

示例文本

"Hello everyone! please join us at: https://oursite.com/. and 
please visit our courses websites: http://courseone.com.eu & http://coursetwo.us. 
For prod use websocket with this url: wss://localhost:4500/websocket/. and 
for staging use this url: ws://localhost:4500/websocket".

目标提取结果

https://oursite.com/
http://courseone.com.eu
http://coursetwo.us
wss://localhost:4500/websocket/
ws://localhost:4500/websocket

问题

原正则表达式/(https?:\/\/[^\s]+)/g仅支持匹配http/https协议的URL,无法覆盖ws/wss类型的WebSocket地址。

修正后的正则表达式

将协议部分扩展为支持http、https、ws、wss:

const urlRegex = /((?:https?|wss?):\/\/[^\s]+)/g;

使用示例

const inputStr = "Hello everyone! please join us at: https://oursite.com/. and please visit our courses websites: http://courseone.com.eu & http://coursetwo.us. For prod use websocket with this url: wss://localhost:4500/websocket/. and for staging use this url: ws://localhost:4500/websocket";
const extractedUrls = inputStr.match(urlRegex);
console.log(extractedUrls);

正则解释

  • (?:https?|wss?):非捕获分组,匹配http/https或ws/wss,?表示s是可选的,兼顾带安全后缀的协议
  • :\/\/:匹配协议与地址之间的固定分隔符
  • [^\s]+:匹配所有非空白字符,直到遇到空格为止,保证完整提取URL内容

内容的提问来源于stack exchange,提问作者StormTrooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:25:23