Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...