Ninja Anime
Ninja Anime

Reputation: 43

Javascript replace a string

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>

Upvotes: 2

Views: 71

Answers (4)

Redu
Redu

Reputation: 26161

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

Upvotes: 0

Fajar F Ramdhan
Fajar F Ramdhan

Reputation: 115

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

Upvotes: 0

Hexiler
Hexiler

Reputation: 203

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

Upvotes: 0

Rion Williams
Rion Williams

Reputation: 76547

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

Upvotes: 1

Related Questions