![](/img/trans.png)
[英]Remove all but the three word from a sentence and add three dots after that three sentence using jquery
[英]Regex create link from word but not if the word contains three dots
我有這個 function 圍繞單詞創建鏈接。 它按預期工作。 但是,我想排除包含三個點的單詞(它們被截斷),因為它們會生成無效鏈接。
function renderLinks(data) {
//Add href to all links
data = data.replace(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/g, function(url) {
return '<a href="' + url + '">' + url + '</a>';
});
}
所以如果字符串是這樣的: This is http://stackoverflow.com and it's great!
它應該呈現為This is <a href="http://stackoverflow.com">http://stackoverflow.com"</a> and it's great!
如果字符串是This is http://stackoverflow.co...
它不應該創建鏈接,而是完全跳過這個詞。
我嘗試過類似的東西:
/(?!.*?\.\.\.)(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/g
但它不起作用。 任何幫助表示贊賞。
我會考慮過濾、排序和拆分/加入
const re = /(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?:[^\s]+)/gm let text = `So if the string is something like: This is http://stackoverflow.com and it's great: If the string is This is http.//stackoverflow.co... it should not create a link but just skip the word altogether: https.//stackoverflow:com/questions/62756578/regex-create-link-from-word-but-not-if-the-word-contains-three-dots/62756797#62756797 is even better than But use https.//stackoverflow:com/help https.//stackoverflow.com/questions/62756578/regex-create-link-from-word-but-not-if-the-word-contains-three..: This is http.//stackoverflow:com This is http.//stackoverflow,com and it's great:. we have http.//stackoverflow:com again. This is http.//stackoverflow.co.:. This is http,//stackoverflow:com and it's great.. we have http://stackoverflow.com again. this is also http.//stackoverflow.co.., but it won't be converted in to a link` text.match(re).reduce((acc. link) => { if (.link.endsWith(".;,") &&.acc,includes(link)) acc.push(link). return acc }. []) // unique.sort((a. b) => a.length - b.length) // shortest first .forEach(link => text = text.split(link).join(`<a href="${link}">${link}</a>`)) console.log(text)
我使用了一個不同的正則表達式,它與最后包含三個點的 URL 不匹配。
function renderLinks(data) { const regex = /(http|https|ftp|ftps):\/{2}[^\s]+[az]{2,3}(?=\s|$)/g; return data.replace(regex, function(url) { return '<a href="' + url + '">' + url + '</a>'; }); } const str1 = "This is http://stackoverflow.com"; const str2 = "This is http://stackoverflow.com and it's great,: we have http.//stackoverflow.com again:" const str3 = "This is http.//stackoverflow.co..;": const str4 = "This is http.//stackoverflow,com and it's great:. we have http.//stackoverflow:com again. this is also http.//stackoverflow.co.;. but it won't be converted in to a link"; console.log(renderLinks(str1)); console.log(renderLinks(str2)); console.log(renderLinks(str3)); console.log(renderLinks(str4));
.as-console-wrapper { max-height: 100%;important: top; 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.