A. El-zahaby
A. El-zahaby

Reputation: 1160

Replace with html tag in javascript

I want to replace any text like this in input: [www.Link-to-be-shortened.com]following link(cut)

I want to replace it with <a href="cuer.esy.es/?f=www.Link-to-be-shortened.com">following link</a>by javascript

I have tried this code :

var UserString = " Hi <br>This article is good , Please visit the following link [www.Link-to-be-shortened.com]following link(cut)";
var SystemString = UserString.replace("[", "");
SystemString = SystemString.replace("]following link(cut)", "");
var a = document.createElement('a');
var linkText = document.createTextNode("following link");
a.appendChild(linkText);
a.title = "following link";
a.href = "http://cuer.esy.es/?f="+SystemString;
document.body.appendChild(a);

But this code does not work well

Upvotes: 2

Views: 79

Answers (1)

Schlaus
Schlaus

Reputation: 19202

Here's a simple example of how to do this with a regular expression:

var UserString = "[www.Link-to-be-shortened.com]Click here(cut)";

var link = UserString.replace(/\[([^\[]+)\]([^(]+)\(cut\)/g, '<a href="cuer.esy.es/?f=$1">$2</a>');

console.log(link);

HOWEVER, this will not work in all possible cases. You could use this if only trusted people are submitting links.

Upvotes: 1

Related Questions