0

I am trying to filter out all URL from a string input. Currently, I have a regex that is able to find URLs starting with http:// or https:// or ftp:// as seen below:

var _input = document.querySelector("#input");
var btn = document.querySelector("#btn");
var results = document.querySelector("#results");

btn.addEventListener("click", function() {
var input_ = _input.value;
var cleanInput = input_.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '');
results.innerHTML = cleanInput;
});
<textarea id="input" rows="5" style="width: 200px;"></textarea>
<button id="btn">SUBMIT</button>
<div id="results"></div>

What Regex should I use to match www.*** and also it should not case sensitive. http or HTTP should also be match.

4
  • 1
    Try .replace(/(?:(?:http|ftp)s?:\/\/|www\.)[\n\S]+/ig, ''); Commented Mar 19, 2019 at 9:59
  • Have you tried to create the regex that you are looking for yourself? If not, you should do that; if so, could you share what you've tried in your question? It helps to show you've put effort into figuring out the problem yourself, and gives answerers a starting point to really help your understanding, rather than to just give you a regular expression that works. Commented Mar 19, 2019 at 10:04
  • This works like magic, thanks @WiktorStribiżew Commented Mar 19, 2019 at 10:04
  • @Florrie I included the code Commented Mar 19, 2019 at 10:05

1 Answer 1

2

You may adjust your regex to

.replace(/(?:(?:http|ftp)s?:\/\/|www\.)[\n\S]+/ig, '');

Details

  • ig - ignore case (i) and global (g) modifiers to match all occurrences in a case insensitive way
  • (?:(?:http|ftp)s?:\/\/|www\.) - https://, http://, ftp://, ftps:// or www.
  • [\n\S]+ - 1 or more non-whitespace or LF chars
Sign up to request clarification or add additional context in comments.

2 Comments

Nice solution. Interesting that you did respect non-whitespace and LF chars. Thumbs up for that
@r3dst0rm It is just the same as OP regex, I only added required fixes.

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.