我有以下功能:
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 值之间?
因此输出应如下所示:
<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:"#
替换为 '/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'));
关于javascript 如何在主题标签上进行正则表达式匹配和替换,但排除主题标签字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585221/