如果包含多个 URL 的字符串中不存在 http://,如何添加它



我正在检查的字符串:

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。我使用下面的逻辑添加它,但这里的问题是,它只检查第一个URL,如果http或httpss不存在,则替换它。没有其他没有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;
}
});
}

有人能告诉我这里出了什么问题吗?

使用g修饰符。如果没有它,您的regexp将只找到第一个匹配项。此外,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));

最新更新