JS 문자열에는 대체 () 메소드가 있습니다. 그러나이 방법은 일치하는 첫 번째 문자열 만 대체합니다. 다음 예에서 볼 수 있듯이 :
<html> <head> <title> 새 문서 </title> </head> <cript> <cript> var str = "wordwordwordword"; var strnew = str.replace ( "Word", "Excel"); alert (strnew); </script> </body> </html>
모든 것을 교체하려면 JS는 replaceall과 같은 방법을 제공하지 않습니다. 규칙 성을 사용하여 교체의 효과를 달성하십시오.
str.replace (/word/g, "xcel") G는 다음을 의미합니다. 글로벌 경기를 수행합니다 (첫 번째 경기를 찾은 후 중지 대신 모든 경기를 찾으십시오).
<head> <title> 새로운 문서 </title> <cript> 함수 replaceall (str) {if (str! = null) str = str.replace (/word/g, "excel") return str;} </script> </head> <스크립트> var str = "wordwordword"; var strnew = str.replace ( "word"); replaceall (str); Alert (strnew); </script> </body> </html>위를 작성하는 유사한 방법이 있습니다.
str.replace (New Regexp ( "Word", "GM"), "Excel") G는 글로벌 경기를 수행합니다 (첫 경기가 발견 된 후 중지 대신 모든 경기를 찾습니다).
m 다중선 일치를 수행합니다.
또한 Stirng 객체의 프로토 타입 방법을 추가 할 수도 있습니다.
String.prototype.replaceall = function (s1, s2) {return this.replace (new regexp (s1, "gm"), s2); }이렇게하면 교체 방법을 사용하는 것처럼 replaceall을 사용할 수 있습니다.
str.replaceall ( "Word", "Excel"); 요약하면 세 가지 방법
1. str.replace (/Oldstring/G, Newstring)
2. str.replace (New Regexp (Oldstring, "GM"), Newstring)
3. 문자열 객체 프로토 타입 메서드를 추가하십시오