我正在檢查的字符串:
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 的字符串,如果 URL 沒有 http 或 https 我正在使用下面的邏輯添加它,但這裡的問題是它只是檢查第一個 URL,如果 http 或 https 不存在則替換它沒有其他沒有 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
修飾符。沒有它,您的正則表達式只會找到第一個匹配項。此外,String.replace()
不返回承諾。你不需要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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句