Front-end/Javascript
JavaScript - String replace()
조미남
2012. 8. 15. 14:56

JavaScript– String replace() 메서드 사용
1.선언
문장의 특정 문자열을 검색하여, 다른 문자로 치환하는 메서드입니다.
대/소문자 구분을 하며, 표현식(/g/i/ 등)을 함께 사용할 수 있습니다.
2.구문
string.replace(regexp/substr,newstring) |
파라미터 | 정의 |
regexp/substr | 표현식 혹은 변경할 문자열을 입력. |
newstring | 필수항목. 변경할 새로운 문자열 |
3.브라우저 지원

replace() 메서드는 모든 브라우저를 지원함,
4.예제
5. 예제 1 대/소문자를 구분하여 검색 < script type="text/__javascript">
var str="Visit Microsoft!"; document.write(str.replace("Microsoft", "W3Schools"));
< /script> |
|
결과 |
6. 예제 2 표현식을 함께 사용하며, 대/소문자 구분검색 < script type="text/__javascript">
var str="Visit Microsoft!"; document.write(str.replace(/microsoft/i, "W3Schools"));
< /script> |
결과 |
7. 예제 3 전체 문장의 대/소문자 문자열을 검색함. 표현식 /g/i/ 는 문장의 모든 일치되는 글자를 변경하라는 것. < 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> |
결과 Welcome to W3Schools! We are proud to announce that W3Schools has one of the largest Web Developers sites in the world. |
|