replace string on 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: str replace javascript all

str.replace(/abc/g, '');

Example 4: javascript replace array element

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