我正在檢查的字串:
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;
}
});
}
任何人都可以讓我知道這里有什么問題嗎?
uj5u.com熱心網友回復:
使用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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371498.html
標籤:javascript 反应 正则表达式
