我想改变这个
[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>
最佳答案
您可能想考虑简单地创建一个函数来为您封装所有这些,特别是如果您计划在应用程序的多个区域中使用 in:
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>');
}
关于Javascript 替换一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43766088/