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?

3
  • Possible duplicate of stackoverflow.com/questions/1500260/… Commented Oct 25, 2011 at 8: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. Commented Oct 25, 2011 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. Commented Oct 26, 2011 at 3:17

1 Answer 1

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

See Detect URLs in text with JavaScript

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

3 Comments

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?
Have a look at regexlib and you will find more regexp for this than you want to know... (I hate regexp ;)
Brrrr, that site scares me ... Thanks :)

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.