开发者

Select substring based on a string of options

I have the following code


// this text box can contain a URL such as:
// http://vimeo.com/
// http://www.youtube.com/
// and so on.
var text = $('#myTextBox').val();
var providers = "youtube|flickr|viddler|qik|revision3|hulu|vimeo";

if( text.match(providers).length > -1) {  
  var selectedProvide开发者_如何学编程r = ???;
}

the match method looks if there are any sub-string that match the list of providers: youtube, flickr, vimeo etc.

My question is which provider was matched?


You can capture the match result and get the first element matched:

var text = $('#myTextBox').val();
var match = text.match("youtube|flickr|viddler|qik|revision3|hulu|vimeo");

if (match) {
  var selectedProvider = match[0];
}

String.prototype.match expects a RegExp object as argument, but if you pass a String, it will be replaced with the result of the expression new RegExp(string)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜