Comment remplacer tous les événements d'une chaîne en JavaScript

Mots clés : javascriptstringreplacejavascript

meilleur 5 Réponses Comment remplacer tous les événements d'une chaîne en JavaScript

vote vote

93

str = str.replace(/abc/g, ''); 
var find = 'abc'; var re = new RegExp(find, 'g');  str = str.replace(re, ''); 
function replaceAll(str, find, replace) {   return str.replace(new RegExp(find, 'g'), replace); } 
function escapeRegExp(string) {   return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } 
function replaceAll(str, find, replace) {   return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } 
vote vote

81

String.prototype.replaceAll = function(search, replacement) {     var target = this;     return target.replace(new RegExp(search, 'g'), replacement); }; 
String.prototype.replaceAll = function(search, replacement) {     var target = this;     return target.split(search).join(replacement); }; 
function escapeRegExp(str) {   return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string } 
vote vote

70

let result = "1 abc 2 abc 3".replaceAll("abc", "xyz"); // `result` is "1 xyz 2 xyz 3" 
str = "Test abc test test abc test...".split("abc").join(""); 
str.split(search).join(replacement) 
vote vote

65

someString = 'the cat looks like a cat'; anotherString = someString.replace(/cat/g, 'dog'); // anotherString now contains "the dog looks like a dog" 
vote vote

57

String.prototype.replaceAll = function (find, replace) {     var str = this;     return str.replace(new RegExp(find, 'g'), replace); }; 
String.prototype.replaceAll = function (find, replace) {     var str = this;     return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace); }; 

Questions similaires