본문 바로가기
JAVASCRIPT/replaceAll 함수 구현

[ JAVASCRIPT ] replaceAll 함수 구현

by 정윤재 2012. 3. 5.

JAVA 의 String 은 replaceAll 이라는게 있어서 모든 문자열을 한번에

바꿀 수 있다.

자바 스크립트도 똑같이 구현 할 수 있는데

아래와 같이 하면 된다.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script language="javascript">
function sub(){
 
 var str_test_date = document.frm.test_date.value;
 
 var test_date  = str_test_date.replaceAll("-","");
 //   / 를 문자열 앞에 , /gi 를 문자열 뒤에 붙여서  replace 해주면 replaceAll  이 구현 된다.
 alert(test_date);
}

String.prototype.replaceAll = function (str1,str2){
 var str    = this;     
 var result   = str.replace(eval("/"+str1+"/gi"),str2);
 return result;
}

</script>
</head>
<body>
<form name="frm">
<input type="text" name="test_date" value="2012-03-05">
<input type="button" onclick="sub();" value="test">
</form>
</body>
</html>


댓글