String replace multiple characters with an asterisk in JavaScript

We are required to write a JavaScript function that takes in a string as the first argument and an array of numbers. Our function should replace all the characters in the string at indices that are specified by the array elements taken as the second argument with an asterisk.

Example

The code for this will be ?

const str = "Lorem ipsum dolor sit amet consectetur adipiscing elit";
const arr = [4, 7, 9, 12, 15];
const replaceWithAsterisk = (str, indices) => {
    let res = '';
    res = indices.reduce((acc, val) => {
        acc[val] = '*';
        return acc;
    }, str.split('')).join('');
    return res;
};
console.log(replaceWithAsterisk(str, arr));

Output

The output in the console ?

Lore* i*s*m *ol*r sit amet consectetur adipiscing elit

How It Works

The function uses the reduce() method to iterate through the indices array. For each index, it replaces the character at that position in the string with an asterisk. The string is first split into an array of characters, modified, then joined back into a string.

Alternative Approach Using for Loop

Here's a more straightforward approach using a traditional for loop:

const replaceWithAsteriskSimple = (str, indices) => {
    let charArray = str.split('');
    for (let i = 0; i < indices.length; i++) {
        if (indices[i] < charArray.length) {
            charArray[indices[i]] = '*';
        }
    }
    return charArray.join('');
};

console.log(replaceWithAsteriskSimple(str, arr));
Lore* i*s*m *ol*r sit amet consectetur adipiscing elit

Handling Edge Cases

It's important to validate indices to prevent errors:

const safeReplaceWithAsterisk = (str, indices) => {
    if (!str || !Array.isArray(indices)) return str;
    
    let charArray = str.split('');
    indices.forEach(index => {
        if (index >= 0 && index < charArray.length) {
            charArray[index] = '*';
        }
    });
    return charArray.join('');
};

// Test with invalid indices
const testStr = "Hello World";
const testIndices = [-1, 5, 20, 3]; // includes invalid indices
console.log(safeReplaceWithAsterisk(testStr, testIndices));
Hel*o World

Conclusion

Replacing characters at specific indices can be achieved using array methods like reduce() or simple loops. Always validate indices to prevent runtime errors and ensure your function handles edge cases gracefully.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements