Home > Software design >  Trying to create a function that replaces letters of a string
Trying to create a function that replaces letters of a string

Time:01-12

I'm doing an exercise where I need to create a function that takes phrase and letter as parameters, and changes the letters of the phrase that are equal to the parameter letter by '*'

function changingLetters(phrase, letter) {
    for (let i = 0; i < phrase.lenght; i  ) {
        if (phrase[i] === letter) {
            phrase[i] = '*'
        }
    }
    return phrase
}

console.log(changingLetters('This is a test','s'))

It's returning the original sentence...

CodePudding user response:

Strings in JavaScript are immutable, meaning you can't change individual characters through the index.

You can convert the string to an array, then set the indicies on the array, and convert it back to a string at the end.

function changingLetters(phrase, letter) {
    const phraseArray = [...phrase];
    for (let i = 0; i < phrase.length; i  ) {
        if (phraseArray[i] === letter) {
            phraseArray[i] = '*'
        }
    }
    return phraseArray.join("");
}

console.log(changingLetters('This is a test','s'))

You also had a typo phrase.lenght -> phrase.length, but that was not the cause of the main issue.


If you want a simple solution,

function changingLetters(phrase, letter) {
    return phrase.replaceAll(letter, "*");
}

console.log(changingLetters('This is a test','s'))

but i think the point of the exercise is that you're supposed to implement this functionality yourself.

CodePudding user response:

This code will not work as expected. JavaScript strings are immutable, meaning that their values cannot be modified once they are created. So when you try to change the value of a character in the string using the code phrase[i] = '*', it will throw an error.

Here is a possible way to write the function using split(), join(), and map() methods

function changingLetters(phrase, letter) {
    return phrase.split('').map(char => char === letter ? '*' : char).join('');
}
console.log(changingLetters('This is a test','s'));

This code will split the string into an array of individual characters, then it will iterate over that array and use the map function to return a new array with the character replaced by '*' if the original character is the same as the letter you passed. and then join back the array of characters to form a string again.

You can also use replace() method

function changingLetters(phrase, letter) {
    return phrase.replace(new RegExp(letter,'gi'),'*');
}
console.log(changingLetters('This is a test','s'));

the replace(new RegExp(letter,'gi'),'') will replace all occurences of letter with '', 'gi' makes the replace operation case-insensitive and global, i.e it will replace all occurence of letter regardless of the case and will match all occurences not just the first one.

  • Related