cycero
cycero

Reputation: 4761

Replace text links with URL-s JavaScript

I have an order submitting form where I want to replace URL texts with corresponding HTML links. I've found the following code on Stackoverflow:

get_url = function() {
  var urls = document.getElementById('w_descr').firstChild;
  urls.nodeValue = replaceURLWithHTMLLinks(urls.nodeValue);
}

function replaceURLWithHTMLLinks(text) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(exp,"<a href='$1'>$1</a>"); 
}

I'm calling the get_url() function on click even of the form submitting button. It works fine. However the submitted orders have a feature of editing. If you edit an order and click on the Submit button again, the function will work again and will duplicate the existing link.

Could anybody help me to figure out how can I prevent that to happen? I mean - how to modify the script above to not to duplicate the links which are already in HTML form.

Thanks in advance.

Upvotes: 0

Views: 508

Answers (1)

Arnout Engelen
Arnout Engelen

Reputation: 6897

Always store the text 'plain' (without the links), and only add the links when outputting the text for display.

When outputting the text for editing, output the 'plain' text.

Upvotes: 1

Related Questions