我的职能如下:
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:属性中的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:",但是我想知道没有第二个替换是否可能?
发布于 2019-10-28 02:52:54
将#移出被捕获的第二组,这样它就不会被捕获。当替换时,在href中,用$2替换(所以不使用hashtag)。当替换<a>中的文本时,用#$2替换,这样就可以在适当的位置添加hashtag:
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'));
发布于 2019-10-28 02:53:43
您只需要将哈希符号移出捕获组;这样做不会更改匹配的语义。就像这样:
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>';
}发布于 2019-10-28 02:54:01
只需添加另一个捕获组,就可以在$2中获得与哈希标记(或任何其他想要捕获的字符)的匹配,并在$3:(#([-.\w]+))而不是(#[-.\w]+)中添加另一个没有hashtag的匹配
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>
https://stackoverflow.com/questions/58585221
复制相似问题