我想改变这个
[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]
进入这个
<a href="http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string">Text</a>
使用javascript
我试过这个。
<script>
var str = "[s=/site_menu.xhtml?get-d=4%2027&get-id=315&get-title=DanMachi%20Season%202&get-main=DanMachi]DanMachi Season 2[/s]";
var res = str.replace("[s=", '<a href="');
var ser = res.replace("[/s]", "</a>");
var serr = ser.replace("]", ':admin-hash-amp:">');
document.write(serr);
</script>
答案 0 :(得分:1)
您可能想要考虑简单地创建一个能够为您封装所有这些内容的函数,特别是如果您打算在应用程序的多个区域内使用它们:
function toHyperLink(input){
return input.replace('[s=','<a href="')
.replace(']','">')
.replace('[/s]','</a>');
}
示例强>
var input = '[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]';
console.log(`Input: ${input}`);
console.log(`Output: ${convertToHyperlink(input)}`);
function convertToHyperlink(input) {
return input.replace('[s=', '<a href="').replace(']', '">').replace('[/s]', '</a>');
}
&#13;
答案 1 :(得分:0)
进行转换后,你应该创建一个元素,而不是写出来。
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]";
var res = str.replace("[s=", '<a href="');
var ser = res.replace("[/s]", "</a>");
var serr = ser.replace("]", '">');
var text = serr.slice(serr.indexOf(">") + 4, serr.indexOf("</a>"))
var href = serr.slice(serr.indexOf("href=\"") + 6, serr.indexOf("\">"))
var link = document.createElement("a");
link.text = text;
link.href = href;
document.getElementById("myDIV").appendChild(link);
答案 2 :(得分:0)
试试这个
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]";
var r = str.replace(/\[s=(.*?)\](.*?)(\[\/s\])/gi,"<a href='$1'>$2</a>");
document.write(r);
答案 3 :(得分:0)
我猜你也可能喜欢;
var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]",
res = str.replace(/\[s(.+)\](.+)\[\/s\]/, "<a href$1>$2</a>");
console.log(res);
&#13;