javascript
  • jquery
  • regex
  • find
  • match
  • 2013-03-14 38 views 2 likes 
    2

    任何工作正则表达式来查找图像的URL?通过使用正则表达式查找图像网址

    例子:

    var reg = /^url\(|url\(".*"\)|\)$/; 
    
    var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")'; 
    
    var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)'; 
    
    
    console.log(string.match(reg)); 
    console.log(string2.match(reg)); 
    

    我绑,但会失败,此reg 格局将是这样的,我只是想图像URL url(" ")

    之间或 url()

    我只是想获得输出像http://domain.com/randompath/random4509324041123213.jpg

    http://jsbin.com/ahewaq/1/edit

    +0

    你只是试图从字符串中提取网址? – 2013-03-14 14:21:55

    +0

    我只想得到像'http:// domain.com/randompath/random4509324041123213.jpg'这样的输出@JamesHill – l2aelba 2013-03-14 14:22:18

    回答

    1

    我简单地使用以下表达式:

    /url.*\("?([^")]+)/ 
    

    这将返回一个阵列,其中所述第一索引(0)包含整个比赛,该第二将URL本身,像这样:

    'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1]; 
    //returns "http://domain.com/randompath/random4509324041123213.jpg" 
    //or without the quotes, same return, same expression 
    'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1]; 
    

    如果有单引号和双引号中使用的改变,你可以简单地通过任何'"['"]更换所有",在这种情况下:

    /url.*\(["']?([^"')]+)/ 
    
    1

    试试这个正则表达式:

    var regex = /\burl\(\"?(.*?)\"?\)/; 
    var match = regex.exec(string); 
    console.log(match[1]); 
    

    URL被捕获在第一个子组中。

    +0

    不行,对不起 – l2aelba 2013-03-14 14:24:38

    +0

    @ l2aelba这不是一个有用的评论。什么不起作用?你提取了第一个小组吗? – speakr 2013-03-14 14:25:19

    +0

    got''“”url(http://domain.com/randompath/random4509324041123213.jpg)“,”http://domain.com/randompath/random4509324041123213.jpg "]'in console.log http:// jsbin。 com/ahewaq/5 /编辑 – l2aelba 2013-03-14 14:26:05

    0

    如果字符串将始终是一致的,其中一个方案是简单地去掉前4个字符url("最后两个")

    var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")'; 
    
    // Remove last two characters 
    string = string.substr(0, string.length - 2); 
    
    // Remove first five characters 
    string = string.substr(5, string.length); 
    

    这里的a working fiddle

    这种方法的好处:您可以自己编辑它,而不要求StackOverflow为您做。 RegEx是很好,但如果你不知道它,用它来代码你的代码会造成令人沮丧的重构。

    相关问题