1

Given an input field, I'm trying to use a regex to find all the URLs in the text fields and make them links. I want all the information to be retained, however.

So for example, I have an input of "http://google.com hello this is my content" -> I want to split that by the white space AFTER this regex pattern from another stack overflow question (regexp = /(ftp|http|https)://(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(/|/([\w#!:.?+=&%@!-/]))?/) so that I end up with an array of ['http://google.com', 'hello this is my content'].

Another ex: "hello this is my content http://yahoo.com testing testing http://google.com" -> arr of ['hello this is my content', 'http://yahoo.com', 'testing testing', 'http://google.com']

How can this be done? Any help is much appreciated!

1
  • (ftp|http|https)://\S+ is enough to get the url part Commented Feb 20, 2017 at 23:53

2 Answers 2

1

First transform all the groups in your regular expression into non-capturing groups ((?:...)) and then wrap the whole regular expression inside a group, then use it to split the string like this:

var regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!-/]))?)/;
var result = str.split(regex);

Example:

var str = "hello this is my content http://yahoo.com testing testing http://google.com";

var regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!-/]))?)/;
var result = str.split(regex);

console.log(result);

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

1 Comment

Thanks! I ended up customizing it after using the regex you provided. thank you for your help @ibrahimmahrir
1

You had few unescaped backslashes in your RegExp.

var str = "hello this is my content http://yahoo.com testing testing http://google.com";
var captured = str.match(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!-/]))?/g);

var nonCaptured = [];
str.split(' ').map((v,i) => captured.indexOf(v) == -1 ? nonCaptured.push(v) : null);

console.log(nonCaptured, captured);

3 Comments

so this works for the url links i want but I also want to capture the non-regex content (i.e. "hello this is my content") into a separate array
forgot to tag you :) @kinduser
thanks! I ended up customizing it a bit after you provided me with the regex @kinduser

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.