Sunday, July 11, 2021

Junior Developer Central JS Practice Exercise - 03

 
Question: 

Write a Javascript program to replace every character in a given string with the character following it in the alphabet. 





Answer: 

function replaceChar (str) {

str001 = str.toString(); 
str001 = str001.split('').map(char => String.fromCharCode(char.charCodeAt(0) + 1)).join('');
return str001;

}





> this function replaces each character of the string with the next character in the alphabet
> we first declare a function "replaceChar'
> it has one parameter 'str'
> we first convert the 'str' parameter to a string using the 'toString() method
> we save it in the variable 'str001'
> we then use the split method on 'str001' to divide the string in to an array of substrings
> after we have split the string 'str001', we use the map method 
> the map method will create a new array 
> this new array will have the result of calling a function for every array element
>> the function in the map basically has two tasks to complete
>> first task is to convert the array elements to its Unicode value and add 1 to it
>> we use the charCodeAt(0) + 1
>> we add 1 to it, as we have to replace the character with the next character in the alphabet
>> so by doing the first task we shall get an array of Unicode values
>> second task is to convert the array of Unicode values we got, into characters
>> so we use the String.fromCharCode() to convert the Unicode value to characters
> thus we have an array of characters by using the map method
> we then need to create a string from the array of characters as that would be our answer
> so we use the join method after the map method to convert it into a string value
> we then return 'str001' to get our final answer which will be a string that has the characters moved forward
> like this: 'abcde' will become 'bcdef'    

No comments:

Post a Comment