使用jquery正则表达式检查起始值


Check the start value with jquery regular expressions

大家好,我想知道我是否可以用jquery检查值的开头,我尝试了这个代码

$('#ads_img').keyup(function(){
if($(this).val() ^= 'http://'){
alert('ok');
}
}); 

但它对我不起作用。

尝试JavaScript indexOf()方法

$('#ads_img').keyup(function() {
  var value = $(this).val();
  if ( value.indexOf("http://") === 0 ) {
    alert('ok');
  }
});

示例:

"stackoverflow.com".indexOf("http://") // return -1, not found so false
"http://stackoverflow.com".indexOf("http://") // return 0, is at beginning so true
"sddsghttp://stackoverflow.com".indexOf("http://") // return 5, is at index 5 so false

您想要使用regex来测试值。。。

var patt = /^http:'/'//gi;
$('#ads_img').keyup(function(){
    if(patt.exec($(this).val())){
        alert('ok');
    }
});