如何用正则表达式替换文本?

时间:2022-02-04 16:49:26

I want to replace a link as plain text format to html format.

我想将链接替换为纯文本格式的html格式。

But I got the issue that, I don't know how to prepend the http:// prefix for the new replacement if in the original link does not exist.

但是我有个问题,如果原始链接中不存在的话,我不知道如何在新的替换之前加上http://前缀。

var text        = "google.com and http://google.com";
var pattern     = /(\b((https?)\:\/\/)?[A-Za-z0-9]+\.(com|net|org))/ig;
text            = text.replace(pattern,"<a href='$1'>$1</a>");

I meant:

我的意思是:

  1. If: google.com will be replaced <a href="http://google.com">google.com</a>
  2. 如果:google.com将被替换为google.com
  3. If: http://google.com will be replaced <a href="http://google.com">http://google.com</a>
  4. 如果:http://google.com将被替换为http://google.com 。

1 个解决方案

#1


3  

Use the overload of String.replace that takes a function:

使用字符串的重载。替换为一个函数:

var text = "google.com and http://google.com";
var pattern = /(\b((https?)\:\/\/)?[A-Za-z0-9]+\.(com|net|org))/ig;

text = text.replace(pattern, function (str, p1)
{
    var addScheme = p1.indexOf('http://') === -1
                    && p1.indexOf('https://') === -1;

    return '<a href="' + (addScheme ? 'http://' : '') + p1 + '">' + p1 + '</a>';
});

// text is:
// '<a href="http://google.com">google.com</a> and <a href="http://google.com">http://google.com</a>'

#1


3  

Use the overload of String.replace that takes a function:

使用字符串的重载。替换为一个函数:

var text = "google.com and http://google.com";
var pattern = /(\b((https?)\:\/\/)?[A-Za-z0-9]+\.(com|net|org))/ig;

text = text.replace(pattern, function (str, p1)
{
    var addScheme = p1.indexOf('http://') === -1
                    && p1.indexOf('https://') === -1;

    return '<a href="' + (addScheme ? 'http://' : '') + p1 + '">' + p1 + '</a>';
});

// text is:
// '<a href="http://google.com">google.com</a> and <a href="http://google.com">http://google.com</a>'