Detect and remove URLs from textarea

jquery, regex

Solution

Try (Corrected and improved after comments):

value = value.replace(/^(\[url=)?(https?:\/\/)?(www\.|\S+?\.)(\S+?\.)?\S+$\s*/mg, '');

Peeling the expression from end to start:

- An address might have two or three 'parts', besides the scheme

- An address might start with www or not

- It my be preceeded by http:// or https://

- It may be enclosed inside [url=...]...[/url]

This expression does not enforce the full correct syntax, that is a much tougher regex to write. A few improvements you might want:

1.Awareness of spaces

value = value.replace(/^\s*(\[\s*url\s*=\s*)?(https?:\/\/)?(www\.|\S+?\.)(\S+?\.)?\S+\s*$\s*/mg, '');

2.Enforce no dots on the last part

value = value.replace(/^(\[url=)?(https?:\/\/)?(www\.|\S+?\.)(\S+?\.)?[^.\s]+$\s*/mg, '');

Problem

``` <textarea name="test"> http://google.com/ https://google.com/ www.google.com/ [url=http://google.com/]google.com[/url] text </textarea> ``` My current attempt at checking if there is a URL in the textarea. ``` if ($('textarea[name="test"]').val().indexOf('[url') >= 0 || $('textarea[name="test"]').val().match(/^http([s]?):\/\/.*/) || $('textarea[name="test"]').val().match(/^www.[0-9a-zA-Z',-]./)) { ``` This doesn't seem to work completely for checking any of the URLs above - I'm wondering how it can be optimized. It seems very sloppy and hacked together at the moment and hopefully someone can shed some insight. My current attempt at removing URLs from the textarea: ``` var value = $('textarea[name="test"]').val(); value = value.replace(/\[\/?url([^\]]+)?\]/g, ''); $('textarea[name="test"]').val(value); ``` Right now, it will output: ``` <textarea> http://google.com/ https://google.com/ www.google.com/ google.com text </textarea> ``` What I'd like my output to be: ``` <textarea> text </textarea> ```

Original source

Related problems