首页 > 编程知识 正文

javascript 字符串截取(正则截取中间字符串)

时间:2023-05-04 21:02:42 阅读:77286 作者:4061

在某些情况下,必须在JavaScript字符串中查找URL。

本文介绍如何在JavaScript字符串中搜索URL并将其转换为链接。

可以创建自己的函数,并使用正则表达式搜索URL。

例如,可以写如下:

const urlify=(text )={

consturlregex=//(https? 3360//[^s](/g;

returntext.replace(urlregex,(url )={

return `a href='${url}${url}/a `;

() )

}

const text=' find meat http://www.example.comandalsoat http://堆栈overflow.com ';

const html=URL ify (文本);

已创建接受console.log(html ) text字符串的urlify函数。

函数优化了具有regex以匹配url的urlRegex变量。

我们检查http或https。

然后找斜线和文本。

正则表达式末尾的g标志允许您搜索字符串中的所有URL。

然后,在urlRegex中调用text.replace,并返回具有与回调匹配的url的字符串。

因此,在文本中调用urlify时,可以执行以下操作:

' findmeatahref=' http://www.example.com http://www.example.com/andalsoatahref=' http://堆栈覆盖.com 3358堆栈操作

例如,可以写如下:

const urlify=(text )={

consturlregex=//(b ) https? |FTP|file(:(/)/[-a-z0-9@#(/%?=~_|! ]*[-A-Z0-9 @#/%=~_|] )/ig;

returntext.replace(urlregex,(url )={

return `a href='${url}${url}/a `;

() )

}

const text=' find meat http://www.example.comandalsoat http://堆栈overflow.com ';

const html=URL ify (文本);

搜索console.log(html ) http、https、ftp和文件url。

图案还包括:字母、和符号和下划线。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。