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

    이미지 URL을 찾으려면 작동하는 정규 표현식이 있습니까?Regex를 사용하여 이미지 URL 찾기

    예 : 난 그냥 싶어

    url(" ") 간 또는 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을 원하는 출력 http://domain.com/randompath/random4509324041123213.jpg

    같은

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

    +0

    문자열에서 URL을 추출하려고합니까? –

    +0

    그냥'http : // domain.com/randompath/random4509324041123213.jpg'과 같은 결과를 얻고 싶습니다. @JamesHill – l2aelba

    답변

    1

    단순히이 표현 사용하십시오 :

    : 이것은 첫 번째 인덱스 (0) 전체 경기가 포함 된 배열을 반환

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

    을, 두 번째는 지금과 같은 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

    +0

    @ l2aelba 이것은 유용한 설명이 아닙니다. 작동하지 않는 것은 무엇입니까? 첫 번째 하위 그룹을 추출 했습니까? – speakr

    +0

    은 console.log http : // jsbin에서'[ "url (http://domain.com/randompath/random4509324041123213.jpg)", "http://domain.com/randompath/random4509324041123213.jpg"]'을 받았습니다. co.kr/ahewaq/5/ – l2aelba

    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는 위대한이지만, 모르는 사람은 코드를 사용하여 좌절시키는 리팩토링을합니다.

    관련 문제