How to find regexp in a string and attach it to a variable
Let's say we have a string开发者_如何学运维 in JavaScript "This is a nice website - http://stackoverflow.com". I want to extract the URL along with the three preceding characters (space dash space) using RegExp and attach the extracted string to a variable.
var string = "This is a nice website - http://stackoverflow.com";
var reg = ""; //no idea how to write this regexp for extracting url and three preceding chars
// and after some magic I would get
var extracedString = " - http://www.stackoverflow.com";
Anyone? Thanks.
var extractedString = string.replace(/^.*(...http:.+)$/, "$1");
if (extractedString == string) {
alert("No match");
}
The dot .
matches every character, so three dots match three arbitrary characters. The ^
and $
match start and end of the string.
Note, that this won't work for
more than one URL
HTTPS, mailto, FTP, SSH, ... (although you can simply expand it, like this:
(https?|ftp|ssh)
)
精彩评论