2

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

1
  • Why dos not work well? any jsfiddle to see it? Commented Feb 3, 2017 at 21:22

1 Answer 1

1

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.

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

Comments

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.