Replace or remove all occurrences of a string

From CodeCodex

Related content:

Implementations[edit]

Erlang[edit]

S = "replace both x and x with a y",
re:replace(S, "x", "y", [global, {return, list}]).

Java[edit]

Java has a built in function for replacing all occurrences of a string. This function accepts regular expressions, so you have to take care to escape characters that might have special meaning.

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

Since Java 1.5, the following is a replace method that does not use regular expressions:

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

JavaScript[edit]

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);
 }
 String.prototype.replaceAll=function(s1, s2) {
    var str = this;
    var pos = str.indexOf(s1);
    while (pos > -1){
		str = str.replace(s1, s2);
		pos = str.indexOf(s1);
	}
    return (str);
}

To use this code:

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

OCaml[edit]

# 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"

Perl[edit]

This function accepts regular expressions.

s{1337}{Elite}g; # replace globally

PHP[edit]

  $new_str = str_replace($remove_this, '', $input);

Python[edit]

new_str = input.replace("x", "y")

Ruby[edit]

This function accepts regular expressions.

str = "replace both x and x with a y"
new_str = str.gsub('x', 'y') # replace globally

Seed7[edit]

var string: s is "replace both x and x with a y";
s := replace(s, "x", "y");

Tcl[edit]

set s "replace both x and x with a y"
string map {x y} $s