2

I'm currently working on a project where we want to limit the amount of characters a user can enter. So far this is working, javascript is used for front-end detection, and on the back-end the string is shortened why a user disabled js.

The only problem are links, we don't want to count links as characters as they will be shortened anyway. Now I'm looking for a way to quickly detect links, find the lenght of that link and ignore it.

The js for it is pretty simple:

var currentLength = $(parent).find('textarea').val().length;
var remaining = max - currentLength;

if(remaining <= 0) {
    $(parent).find('textarea').val($(parent).find('textarea').val().substr(0, max));
    remaining = 0;
}

Anybody that can point me in the right direction on how to do this? Maybe something with regular expressions?

woutr_be
  • 9,532
  • 24
  • 79
  • 129
  • Possible duplicate of http://stackoverflow.com/questions/1500260/detect-urls-in-text-with-javascript – vzwick Oct 25 '11 at 08:33
  • Despite an answer has been already excepted: What are you using in the back-end to recognize the link when they are being shortened? Most likely it's a regular expression, too, and most likely it should be possible to use the same regular expression (maybe adjusted for syntax differences), which would be much more reliable. – RoToRa Oct 25 '11 at 13:19
  • Yes, I'm using regular expressions in the back-end as well, but due to my lack of knowledge of it, I wasn't able to port it to JS. – woutr_be Oct 26 '11 at 03:17

1 Answers1

1
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, '');

See Detect URLs in text with JavaScript

Community
  • 1
  • 1
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
  • Oh thanks, I totally overlooked that one, now this regex only detects links with http in front of them. Since I'm really bad with regex, how would I also be able to detect links with www in front of it? Or even just google.com? – woutr_be Oct 25 '11 at 08:36
  • Have a look at [regexlib](http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1) and you will find more regexp for this than you want to know... (I hate regexp ;) – PiTheNumber Oct 25 '11 at 08:39
  • Brrrr, that site scares me ... Thanks :) – woutr_be Oct 25 '11 at 08:59