Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to replace all occurrences of a substring in a string with JavaScript

6 Answers

0 votes
let s = "javascript php c++ PHP css php";
    
s = s.replace(/\php/gi, 'c#');
   
console.log(s);
    
    
    
    
/*
run:
    
"javascript c# c++ c# css c#"
   
*/

 



answered Sep 22, 2019 by avibootz
edited Feb 2, 2021 by avibootz
0 votes
String.prototype.replaceAll = function(search_s, replace_s) {
    let s = this;
  
    return s.replace(new RegExp(search_s, 'gi'), replace_s);
};
  
   
let s = "javascript php c++ PHP css php";
   
s = s.replaceAll('php', 'c#');
  
console.log(s);
   
   
   
   
/*
run:
   
"javascript c# c++ c# css c#"
  
*/

 



answered Oct 29, 2019 by avibootz
edited Feb 2, 2021 by avibootz
0 votes
String.prototype.replaceAll = function(search_s, replace_s) {
    let s = this;
      
    return s.split(search_s).join(replace_s);
};
  
   
let s = "javascript php c++ PHP css php";
   
s = s.replaceAll('php', 'c#');
   
console.log(s);
    
    
    
    
    
/*
run:
    
"javascript c# c++ PHP css c#"
   
*/

 



answered Oct 29, 2019 by avibootz
edited Feb 2, 2021 by avibootz
0 votes
let s = "c# javascript c# c++ java c# php c#";
 
s = s.replace(/c#/g, '');
 
console.log(s);
         
 
/*
 
run:
 
 javascript  c++ java  php 
 
*/

 



answered Apr 23, 2024 by avibootz
0 votes
function replaceAll(s, find, replace) {
    return s.replace(new RegExp(find, 'g'), replace);
}

let s = "c# javascript c# c++ java c# php c#";
 
s = replaceAll(s, 'c#', ' ');
 
console.log(s);

         
 
/*
 
run:
 
  javascript   c++ java   php  
 
*/

 



answered Apr 23, 2024 by avibootz
0 votes
let s = "c# javascript c# c++ java c# php c#";
 
s = s.split('c#').join(' ').trim();
console.log(s);

s = s.replace(/\s\s+/g, ' ');
console.log(s);

         
 
/*
 
run:
 
javascript   c++ java   php
javascript c++ java php
 
*/

 



answered Apr 23, 2024 by avibootz
...