Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting for URL from string using regex

I want to extract the first valid URL in a string, which can be anywhere between characters and whitespace

I have tried with the following

...
urlRegex: /^(http[s]?:\/\/.*?\/[a-zA-Z-_]+.*)$/,

...
var input = event.target.value // <--- some string;
var url   = input.match(this.urlRegex);

Problem is url returns the whole string when it finds a url, instead of returning just the part of the string matching the regex

Example The string

https://medium.com/aspen-ideas/there-s-no-blueprint-26f6a2fbb99c random stuff sd

returns

["https://medium.com/aspen-ideas/there-s-no-blueprint-26f6a2fbb99c random stuff sd", "https://medium.com/aspen-ideas/there-s-no-blueprint-26f6a2fbb99c random stuff sd", index: 0, input: "https://medium.com/aspen-ideas/there-s-no-blueprint-26f6a2fbb99c random stuff sd"]

How can this be achieved?

like image 324
Tarlen Avatar asked Dec 06 '25 16:12

Tarlen


2 Answers

Your regex is incorrect.

Correct regex for extracting URl : /(https?:\/\/[^ ]*)/

Check out this fiddle.

Here is the snippet.

var urlRegex = /(https?:\/\/[^ ]*)/;

var input = "https://medium.com/aspen-ideas/there-s-no-blueprint-26f6a2fbb99c random stuff sd";
var url = input.match(urlRegex)[1];
alert(url);
like image 167
Shrinivas Shukla Avatar answered Dec 09 '25 15:12

Shrinivas Shukla


  • You haven't included digits in your regex as part of URL.
  • Assuming URL starts from the beginning of the string

Live Demo with regex explanation on left side.

Regex explanation

var regex = /^(https?:\/\/[^/]+(\/[\w-]+)+)/;
var str = 'https://medium.com/aspen-ideas/there-s-no-blueprint-26f6a2fbb99c random stuff sd';

var url = str.match(regex)[0];
document.write(url);
like image 38
Braj Avatar answered Dec 09 '25 15:12

Braj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!