The first time you find the Replace () method in JavaScript If you use Str.replace directly ("-", "!") Only the first matching character is replaced.
and Str.replace (/\-/g, "!") You can replace all matching characters (G is the global flag).
Replace ()
The Replace () method returns the string that results if you replace text matching its first argument
(a regular expression) with the text of the second argument (a string).
If the G (global) flag is not set in the regular expression declaration, this method replaces only the first
Occurrence of the pattern. For example,
var s = "Hello." Regexps is fun. " ; s = s.replace (/\./, "!" ); Replace first period with an exclamation pointalert (s);
Produces the string "hello! Regexps is fun. " Including the G flag would cause the interpreter to
Perform a global replace, finding and replacing every matching substring. For example,
var s = "Hello." Regexps is fun. " ; s = s.replace (/\./g, "!" ); Replace all periods with exclamation pointsalert (s);
Yields this result: "hello! Regexps is fun! "
So there are several ways to do this:
String.Replace (/reallydo/g, replacewith);
String.Replace (New RegExp (Reallydo, ' G '), replacewith);
string expression containing the substring to be substituted.
Reallydo: the substring being searched.
ReplaceWith: Substring used for substitution.
JS Code
- <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>
Source: http://fuleonardo.iteye.com/blog/339749