본문 바로가기

잼있냐JavaScript

javascript - replace("find","replacestr")


자바 스크립트에서 replace() 함수는
의 기능에서 반복되는 문자가 있을 시  예를 들어 (-) 하이픈 --;;

날짜에 2008-11-06 이라는 날짜 문자에서 - 을 모두 '' 로 처리 하고 싶다고 가정한다면

JAVA 에서는 replaceAll 메소드가 있지만..

javascript 에서는 그런 메소드가 없다...

이럴 때는...

아래 예재를 참고 하길 바란다.

Example 3 - Global Search

In the following example we will perform a global match, and the word Microsoft will be replaced each time it is found:

<script type="text/javascript">
var str="Welcome to Microsoft! ";
str=str + "We are proud to announce that Microsoft has ";
str=str + "one of the largest Web Developers sites in the world.";
document.write(str.replace(/Microsoft/g, "W3Schools"));
</script>

The output of the code above will be:

Welcome to W3Schools! We are proud to announce that W3Schools
has one of the largest Web Developers sites in the world.


Example 4 - Global and Case-insensitive Search

In the following example we will perform a global and case-insensitive match, and the word Microsoft will be replaced each time it is found, independent of upper and lower case characters:

<script type="text/javascript">
var str="Welcome to Microsoft! ";
str=str + "We are proud to announce that Microsoft has ";
str=str + "one of the largest Web Developers sites in the world.";
document.write(str.replace(/microsoft/gi, "W3Schools"));
</script>

The output of the code above will be:

Welcome to W3Schools! We are proud to announce that W3Schools
has one of the largest Web Developers sites in the world.

'잼있냐JavaScript' 카테고리의 다른 글

야구게임  (0) 2008.10.22
시를 출력해주는 클래스  (0) 2008.10.22
Color Table  (0) 2008.10.22
Magic Number  (0) 2008.10.22
로또 번호  (0) 2008.10.22