【问题标题】:How to add http:// if it doesn't exist in a string containing multiple URLs如果包含多个 URL 的字符串中不存在 http://,如何添加它
【发布时间】:2022-01-08 17:54:42
【问题描述】:

我正在检查的字符串:

   Unroll the pastry on to a lightly floured work surface. Cut is [Google](www.google.com/) 
    into 2 long rectangles. Cut the large rectangle in half lengthways, then cut both smaller reckk
    Bake in the oven for 25–30 minutes, or until the pastry has turned golden-brown and looks crisp. 
    Remove from the oven and leave to cool slightly before serving. Unroll the pastry on to a lightly floured work surface. 
    this is my [web](www.stackoverflow.com), this is [Google](https://www.google.com/) 
    Cut into 2 long rectangles. Cut the large rectangle in half lengthways, then cut both smaller rectangles into eight equal sections. You now have 16 rectangles in total.
    Brush one end of each rectangle with a little of the beaten egg

如果 URL 没有 http 或 https,上面是我检查 URL 的字符串t 不存在其他没有 http 或 https 的 URL 被更改

以下是我应用的逻辑:

  async urlify(text) {
   var urlRegex = new RegExp(
  '([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?'
   );
  return await text.replace(urlRegex, (url) => {
   if (url.search(/^http[s]?\:\/\//) === -1) {
    return 'http://' + url;
   } else {
     return url;
   }
  });
  }

谁能告诉我这里出了什么问题?

【问题讨论】:

  • 为什么函数是异步的?它不需要是
  • 这也是一些非常有缺陷的逻辑,考虑到 TLD 可以超过 4 个字符,并且主机名根本不需要任何点分隔符即可工作。所以自然需要做出一些权衡,但是是的。需要记住的一点。
  • 看起来像 MarkDown 链接,为什么不直接使用 MarkDown 解析器将文本转换为 HTML?

标签: javascript reactjs regex


【解决方案1】:

使用g 修饰符。没有它,您的正则表达式只会找到第一个匹配项。 此外,String.replace() 不会返回 Promise。你不需要await

const str = ` Unroll the pastry on to a lightly floured work surface. Cut is [Google](www.google.com/) 
    into 2 long rectangles. Cut the large rectangle in half lengthways, then cut both smaller reckk
    Bake in the oven for 25–30 minutes, or until the pastry has turned golden-brown and looks crisp. 
    Remove from the oven and leave to cool slightly before serving. Unroll the pastry on to a lightly floured work surface. 
    this is my [web](www.stackoverflow.com), this is [Google](https://www.google.com/) 
    Cut into 2 long rectangles. Cut the large rectangle in half lengthways, then cut both smaller rectangles into eight equal sections. You now have 16 rectangles in total.
    Brush one end of each rectangle with a little of the beaten egg`;
    
function urlify(text) {
   var urlRegex = new RegExp(
    '([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?', 
    'g'
   );
  return text.replace(urlRegex, (url) => {
   if (url.search(/^http[s]?\:\/\//) === -1) {
    return 'http://' + url;
   } else {
     return url;
   }
  });
}
  
console.log(urlify(str));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2017-03-21
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多