How to replace the first occurrence of a substring in a string with Node.js

1 Answer

0 votes
function replaceFirst(input, search, replace) {
    const index = input.indexOf(search);

    if (index === -1) return input;

    return input.substring(0, index) + replace + input.substring(index + search.length);
}

const s = "aa bb cc dd ee cc ff";
const result = replaceFirst(s, "cc", "ZZ");

console.log(result);


 

/*
run:
  
aa bb ZZ dd ee cc ff
     
*/
 

 



answered Jul 20, 2025 by avibootz
...