簡體   English   中英

javascript 如何在主題標簽上進行正則表達式匹配和替換,但排除主題標簽字符

[英]javascript how to regex match and replace on hashtags but exclude the hashtag character

我有以下 function:

function formattedTitle(posttitle,hreflink) {
  return `<a href='`+ hreflink +`'>` + posttitle.replace(/(^|\s)(#[-.\w]+)/gi, `$1</a><a class="hashtag" href='/search?q=hashtag:"$2"'>$2</a><a href='`+ hreflink + `'>`) + '</a>';
}

當我跑

console.log(formattedTitle('This is #awesome news','google.com'));

它輸出:

<a href='google.com'>This is </a><a class="hashtag" href='/search?q=hashtag:"#awesome"'>#awesome</a><a href='google.com'> news</a>

 function formattedTitle(posttitle, hreflink) { return `<a href='` + hreflink + `'>` + posttitle.replace(/(^|\s)(#[-.\w]+)/gi, `$1</a><a class="hashtag" href='/search?q=hashtag:"$2"'>$2</a><a href='` + hreflink + `'>`) + '</a>'; } console.log(formattedTitle('This is #awesome news', 'google.com'));

注意它是如何在 $2 匹配中包含“#”的。 如何排除hashtag:屬性中的主題標簽字符,但將其保留在 href 值之間?

所以 output 應該如下所示:

<a href='google.com'>This is </a><a class="hashtag" href='/search?q=hashtag:"awesome"'>#awesome</a><a href='google.com'> news</a>

我已經能夠通過對整個事物進行另一次替換以替換'/search?q=hashtag:"# with '/search?q=hashtag:"來使其工作,但我想知道是否可以不進行第二次替換?

#移到捕獲的第二組之外,因此它不會被捕獲。 替換時,在href中,僅替換為$2 (因此沒有主題標簽)。 替換<a>中的文本時,請替換為#$2 ,以便將主題標簽添加到正確的位置:

 function formattedTitle(posttitle, hreflink) { return `<a href='` + hreflink + `'>` + posttitle.replace(/(^|\s)#([-.\w]+)/gi, `$1</a><a class="hashtag" href='/search?q=hashtag:"$2"'>#$2</a><a href='` + hreflink + `'>`) + '</a>'; } console.log(formattedTitle('This is #awesome news', 'google.com'));

您只需要將 hash 符號移出捕獲組即可; 這樣做不會改變匹配的語義。 像這樣:

function formattedTitle(posttitle, hreflink) {
  return `<a href='`+ hreflink +`'>` + posttitle.replace(/(^|\s)#([-.\w]+)/gi, `$1</a><a class="hashtag" href='/search?q=hashtag:"$2"'>$2</a><a href='`+ hreflink + `'>`) + '</a>';
}

只需添加另一個捕獲組,以便您在$2中獲得與主題標簽(或您想要捕獲的任何其他字符)的匹配,並在$3中獲得另一個沒有主題標簽的匹配: (#([-.\w]+))而不是比(#[-.\w]+)

 function formattedTitle(postTitle, href) { const parts = postTitle.replace( /(^|\s)(#([-.\w]+))/gi, `$1</a><a class="hashtag" href="/search?q=hashtag:$3">$2</a><a href="${ href }">`); return `<a href="${ href }">${ parts }</a>`; } document.getElementById('postTitle').innerHTML = formattedTitle('This is #awesome news', 'https://google.com');
 h3 { font-family: monospace; font-size: 24px; margin: 8px 0; } a { padding: 8px 0; text-decoration: none; display: inline-block; }.hashtag { padding: 6px 8px; border: 3px solid blue; border-radius: 3px; margin: 0 8px; }
 <h3 id="postTitle"></h3>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM