简体   繁体   English

JS - 如何在正则表达式中替换链接

[英]JS - how to replace   in regex for links

I have a regex that replaces the link from the moment http to the occurrence of certain characters in [] , I would like to add  我有一个正则表达式替换了从 http 到[]中某些字符出现的链接,我想添加  to these characters - that is to replace the string with the occurrence of certain characters or a hard space:到这些字符 - 即用某些字符或硬空格的出现替换字符串:

"https://test.pl'".replace(/https?:\/\/[^ "'><]+/g," ")

Works fine for the characters mentioned in [] , I don't know how to add here &nbsp ;对于[]中提到的字符工作正常,我不知道如何在这里添加&nbsp ;

You can use您可以使用

.replace(/https?:\/\/.*?(?:&nbsp;|[ '"><]|$)/g," ")

See the regex demo .请参阅正则表达式演示

Details :详情

  • https?:\/\/ - http:// or https:// https?:\/\/ - http://https://
  • .*? - any zero or more chars other than line break chars as few as possible - 尽可能少的换行字符以外的任何零个或多个字符
  • (?:&nbsp;|[ '"><]|$) - one of the following: (?:&nbsp;|[ '"><]|$) - 以下之一:
    • &nbsp; - &nbsp; - &nbsp; char sequence字符序列
    • | - or - 或者
    • [ "'><] - a space, " , ' , > or < char [ "'><] - 空格、 "'><字符
    • | - or - 或者
    • $ - end of string. $ - 字符串结尾。

JavaScript demo: JavaScript 演示:

 const texts = ["https://test.pl&nbsp;test","https://test.pl'test"]; const re = /https?:\/\/.*?(?:&nbsp;|[ '"><]|$)/g; for (const s of texts) { console.log(s, '=>', s.replace(re, " ")); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM