如何将文本分割为URL与空格分隔短语组成的数组?
基于URL分割文本并保留URL的解决方案
问题需求
需要将包含URL的文本以URL为分割点拆分,同时保留URL本身。示例如下:
输入文本:
const text = 'hello world, testing https://stackoverflow.com/questions/ask this is prefix https://gmail.com final text'
期望输出:
const result = [ 'hello world, testing', 'https://stackoverflow.com/questions/ask', 'this is prefix', 'https://gmail.com', 'final text' ]
此前尝试的正则表达式/(http|https):\/\/[a-zA-Z0-9\-.]+\.[a-zA-Z]{2,3}(\/\S*)?/分割效果不稳定,无法满足需求。
解决方案
利用带捕获组的正则表达式配合split方法,同时过滤空字符串即可实现目标。
优化后的正则表达式
/(https?:\/\/\S+)/
https?:\/\/匹配http或https协议前缀\S+匹配任意非空白字符,确保捕获完整的URL(直到遇到空格终止)
实现代码
const text = 'hello world, testing https://stackoverflow.com/questions/ask this is prefix https://gmail.com final text'; const regex = /(https?:\/\/\S+)/; const result = text.split(regex).filter(item => item.trim() !== ''); console.log(result);
原理说明
- 正则中的捕获组
()会让split方法将分割符(即URL)也纳入结果数组,而非直接丢弃。 filter方法用于清除分割后产生的空字符串(比如文本首尾出现URL的场景)。
内容的提问来源于stack exchange,提问作者Pradip Shrestha
相关产品推荐
相关产品推荐

