replace text array javascript code example

Example 1: replace array element javascript

// Replace 1 array element at index with item 
arr.splice(index,1,item);

Example 2: replace all occurrences of a string in javascript

const p = 'dog dog cat rat';

const regex = /dog/gi;

console.log(p.replace(regex, 'cow'));
//if pattern is regular expression all matches will be replaced
//output: "cow cow cat rat"

Example 3: how to replace all the string in javascript when the string is javascript variable

function name(str,replaceWhat,replaceTo){
    replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    var re = new RegExp(replaceWhat, 'g');
    return str.replace(re,replaceTo);
}

Example 4: javascript replace array element

array.splice(array.indexOf(valueToReplace), 1, newValue);