JS Replace
2153 ワード
JavaScriptでreplace()メソッドが直接str.replace(-"!)で最初のマッチする文字だけを置き換えることができますが、str.replace(/-/g)!)では、マッチした文字をすべて置き換えることができます.replace()
The replace()method returns the streing that replace text matching its first argment(a reglar expression)with the text of the second argment(a string)
If the g flobal flag s is not set in the reglar expression declaration,this method replacces only the first occurrence of the pattern.For example,var="Hello.Regexps are fun."s=s.replace(/./,"!)///.replace first period with an exclamation pointalert(s);produces the streing“Hello!Regexps are fun.”Including the g flaglagcause the interpreter to perform a global replace,finding and repling everry matching substring.For exple,var=“Hello.Regexps.”s=s.replace(/./g,"!)//.replace all periods with exclamation pointsalert(s);yields this reult:"Hello!Regexps are fun!"だから以下のいくつかの方法を使うことができます.:string.replace(/reallyDo/g,replace With);string.replace(new RegExp);string:文字列表現には、代替するサブ文字列が含まれています.reallyDo:検索されたサブ文字列.replace With:置換のためのサブ文字列.Jsコード
The replace()method returns the streing that replace text matching its first argment(a reglar expression)with the text of the second argment(a string)
If the g flobal flag s is not set in the reglar expression declaration,this method replacces only the first occurrence of the pattern.For example,var="Hello.Regexps are fun."s=s.replace(/./,"!)///.replace first period with an exclamation pointalert(s);produces the streing“Hello!Regexps are fun.”Including the g flaglagcause the interpreter to perform a global replace,finding and repling everry matching substring.For exple,var=“Hello.Regexps.”s=s.replace(/./g,"!)//.replace all periods with exclamation pointsalert(s);yields this reult:"Hello!Regexps are fun!"だから以下のいくつかの方法を使うことができます.:string.replace(/reallyDo/g,replace With);string.replace(new RegExp);string:文字列表現には、代替するサブ文字列が含まれています.reallyDo:検索されたサブ文字列.replace With:置換のためのサブ文字列.Jsコード
<script type="text/javascript"> String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { if (!RegExp.prototype.isPrototypeOf(reallyDo)) { return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith); } else { return this.replace(reallyDo, replaceWith); } } </script>