在某些情况下,必须在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。
图案还包括:字母、和符号和下划线。