본문 바로가기
Javascript/jQuery

자바스크립트에서 url() 제외하기

by 폴리글랏 2020. 11. 23.

자바스크립트 또는 jQuery로 background-image같은 css 요소를 가져오게 되면 url이 붙어있는 경우가 있다.

 

예를 들어 아래와 같은 코드일 때 주석으로 써둔것처럼 background-image로 가져오게 되면

 

url("C:\경로\test.jpg") 라는 식으로 나오게 된다. 이 부분에서 url("")를 제거해주는 것이다.

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title> new document </title>
	<meta charset="utf-8" />
<style>
.photo_box:nth-child(1) .photo_view {
	background-image: url(img/test.png);
	background-size: 340px;
	background-position: center center;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).on("click", ".photo_box", function() {
    // 현재 요소로부터 photo_view 자식 요소를 찾고 거기서 background-image라는
    // css 요소를 가져와서 url부분을 제거해준다.
    var url = $(this).find(".photo_view").css("background-image");
    url = url.replace(/^url\(['"](.+)['"]\)/, '$1'));
    console.log(url);
});
</script>
</head>
<body>
<div class="photo_box">
	<div class="photo_view">TEST</div>
</div>
</body>
</html>

댓글