sourlemonaid sourlemonaid - 2 months ago 8
Javascript Question

Javascript replace characters of an element in an array

I am trying to replace characters within an array of strings.

so far i have this:

stuff= ["uyuuyu", "76gyuhj***", "uiyghj", "56tyg", "juijjujh***"];

for(var i = 0; i < stuff.length; i++)
{
if(stuff[i].indexOf('***') != -1)
{
// this is where i guess the replacing would go
}
}


I figured out that i can use this code to display with element in the array has the characters *** now want to replace the
***
characters with a number so that it outputs a new array ( the same array but modified) that looks like :

stuff= ["uyuuyu", "76gyuhj0", "uiyghj", "56tyg", "juijjujh0"];


I can't seem to figure out how to replace the characters within that array without effecting the rest of the array

Answer

Also consider .replace(/\*\*\*/g, '0') if you want to replace multiple occurrences of ***. (The below code only replaces the first occurrence in each string.)

stuff= ["uyuuyu", "76gyuhj***", "uiyghj", "56tyg", "juijjujh***"];

for(var i = 0; i < stuff.length; i++)
{
    stuff[i] = stuff[i].replace('***', '0');
}

console.log(stuff);

Note that there's no need to check indexOf. If the substring isn't present, the replace just doesn't change anything, so you can just apply the replace to every string.

Comments