简体   繁体   中英

Why missing one character from my regex?

I have a very good regex function which call in here:

<input onkeyup="vimeo();">

But the problem is, when the user paste a link in to the input, he get this link:

//player.imeo.com/video/VIDEOID

You see? Missing "v" from vimeo and I can't pass on this problem. If I delete the "/" character before of "v" I get repeated value, for example:

//player.player.player.player.player.player.player.player.vimeo.com/video/VIDEOID

My replace script looks like this:

var vimeo = function(){
  var str2;
  $('#url').keyup(function(){
    str2 = $(this).val();
    $(this).val(str2.replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '\/\/player/\.\vimeo\.\com\/video/$1'));
  });
};

How can I fix missing "v" without repeat any value?

Update:

Demo link is here:

http://neocsatblog.mblx.hu/addvideos/

The problem is your replacement string. You don't need to escape any characters. The second argument of the replace method takes a string, not another regular expression.

'\/\/player/\.\vimeo\.\com\/video/$1'

You can just do this:

'//player.vimeo.com/video/$1'

I am not sure why you are using a keyup event on your input as well as your url element, however.

I changed your function a bit and it works for me.

EDIT Since you want to only use one field, you'll need to use onchange to format the url once the user is done editing. I've changed the function to reflect this change. Notice, you don't even need jQuery anymore.

 var vimeo = function(elem) { var str2 = elem.value; elem.value = str2.replace(/(?:http:\\/\\/)?(?:www\\.)?(?:vimeo\\.com)\\/(.+)/g, '//player.vimeo.com/video/$1'); }; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input onchange="vimeo(this);"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM