Difference between revisions of "Replace or remove all occurrences of a string"

From CodeCodex

m
(Implementations)
Line 18: Line 18:
 
int numberOfCommas = s.replaceAll("x","y");
 
int numberOfCommas = s.replaceAll("x","y");
 
</pre>
 
</pre>
 +
===OCaml===
 +
# let replace input output =
 +
    Str.global_replace (Str.regexp_string input) output;;
 +
val replace : string -> string -> string -> string = <fun>
 +
For example:
 +
# replace "133t" "Elite" "133t H4x0r";;
 +
- : string = "Elite H4x0r"
  
 
[[Category:JavaScript]]
 
[[Category:JavaScript]]
 
[[Category:Java]]
 
[[Category:Java]]
 
[[Category:String]]
 
[[Category:String]]

Revision as of 02:37, 11 February 2007

Implementations

JavaScript

String does not have a replaceAll function in JavaScript. To create such a function, use the code below. This function accepts regular expressions.

        String.prototype.replaceAll=function(s1, s2) { 
	  return this.replace(new RegExp(s1,"g"), s2);
	}

To use this code:

        text = 'replace both x and x with a y';
        finalText = text.replaceAll('[x]','y');

Java

Java has a built in function for replacing all occurrences of a string. This function accepts regular expressions.

	String s = "replace both x and x with a y";
	int numberOfCommas = s.replaceAll("x","y");

OCaml

# let replace input output =
    Str.global_replace (Str.regexp_string input) output;;
val replace : string -> string -> string -> string = <fun>

For example:

# replace "133t" "Elite" "133t H4x0r";;
- : string = "Elite H4x0r"