How to replace the first occurrence of a substring in a string with JavaScript

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";
const result = replaceFirst(s, "cc", "YY");

console.log(result);

 

/*
run:
  
aa bb YY dd ee cc
     
*/

 



answered Jul 20 by avibootz
...