2

I want to change this

[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]

into this

 <a href="http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string">Text</a>  

using javascript

I have try this one.

<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=", '&lt;a href="');
var ser = res.replace("[/s]", "&lt;/a&gt;");
var serr = ser.replace("]", ':admin-hash-amp:"&gt;');
document.write(serr);
</script>

4 Answers 4

1

You may want to consider simply creating a function that would encapsulate all of this for you, especially if you plan on using in within multiple areas of your application:

function toHyperLink(input){
    return input.replace('[s=','<a href="')
                .replace(']','">')
                .replace('[/s]','</a>');
}

Example

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>');
}

Sign up to request clarification or add additional context in comments.

Comments

0

After you do your convert you should create an element instead of write that out.

var str = "[s=http://stackoverflow.com/questions/ask?title=Javascript%20replace%20a%20string]Text[/s]";
var res = str.replace("[s=", '&lt;a href="');
var ser = res.replace("[/s]", "&lt;/a&gt;");
var serr = ser.replace("]", '"&gt;');    

var text = serr.slice(serr.indexOf("&gt;") + 4, serr.indexOf("&lt;/a&gt"))
var href = serr.slice(serr.indexOf("href=\"") + 6, serr.indexOf("\"&gt"))

var link = document.createElement("a");
link.text = text;
link.href = href;

document.getElementById("myDIV").appendChild(link);

Comments

0

Try this

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);

Comments

0

I guess you may also do like;

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);

1 Comment

i want to <a href="stackoverflow.com">text</a> change this little bit <a href="stackoverflow.com(want to put some text here)">text</a> pls help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.