J’ai cette chaîne de caractères dans mon code JavaScript :
"Hello xxxx hello hello hello xxxx hello hello hello xxxx"
En faisant ça:
str = str.replace('xxxx', '');
Il me paraît qu’il ne supprime que la première occurrence de xxxx dans la chaîne de caractères.
Comment puis-je remplacer toutes les occurrences de xxxx ?
Isaac
2
Méthode 1: replace()
Vous pouvez utiliser la méthode replace() de JavaScript comme suit:
str = "Hello xxxx hello hello hello xxxx hello hello hello xxxx";
str = str.replace(/xxxx/g, '');
console.log(str)
Sortie:
Hello hello hello hello hello hello hello
Méthode 2: RegExp()
Ou bien vous pouvez utiliser la méthode RegExp() de JavaScript comme suit:
var str = "Hello xxxx hello hello hello xxxx hello hello hello xxxx";
var find = 'xxxx';
var re = new RegExp(find, 'g');
str = str.replace(re, '');
console.log(str)
Sortie:
Hello hello hello hello hello hello hello
Méthode 3: replaceAll()
Ou bien vous pouvez utiliser la méthode replaceAll() de JavaScript comme suit:
var str = "Hello xxxx hello hello hello xxxx hello hello hello xxxx";
str = str.replaceAll("xxxx", "");
console.log(str)
Sortie:
Hello hello hello hello hello hello hello
Méthode 4: split() et join()
Vous pouvez aussi utiliser les méthode split() et join() de JavaScript comme suit:
var str = "Hello xxxx hello hello hello xxxx hello hello hello xxxx";
str = str.split("xxxx").join("");
console.log(str)
Sortie:
Hello hello hello hello hello hello hello
Henri
3
Essayer le méthode suivante, ça fonctionne bien pour moi:
var str = "Hello xxxx hello hello hello xxxx hello hello hello xxxx";
while(str.includes("xxxx")){
str = str.replace("xxxx", "");
}
console.log(str) // Hello hello hello hello hello hello hello
Je vous recommande de voir les tutoriels suivants: